新聞中心
Python之numpy中怎么使用mask?這個問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!
numpy中矩陣選取子集或者以條件選取子集,用mask是一種很好的方法。
簡單來說就是用bool類型的indice矩陣去選擇。
mask = np.ones(X.shape[0], dtype=bool) X[mask].shape mask.shape mask[indices[0]] = False mask.shape X[mask].shape X[~mask].shape (678, 2) (678,) (678,) (675, 2) (3, 2)
例如我們這里用來選取全部點中KNN選取的點以及所有剩余的點。
from sklearn.neighbors import NearestNeighbors nbrs = NearestNeighbors(10).fit(X) _,indices = nbrs.kneighbors(X) mask = np.ones(X.shape[0], dtype=bool) mask[indices[0]] = False plt.scatter(X[mask][:,0],X[mask][:,1],c='g') plt.scatter(X[~mask][:,0],X[~mask][:,1],c='r')
帶條件選擇替換,比如我們需要將a矩陣內(nèi)某條件的行置換為888剩余置換為999,可以直接用mask或者再用where一步搞定:
mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool) mask[indices] = False a[~mask] = 999 a[mask] = 888 ############# np.where(mask, 888, 999)
感謝各位的閱讀!看完上述內(nèi)容,你們對Python之numpy中怎么使用mask大概了解了嗎?希望文章內(nèi)容對大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站題目:Python之numpy中怎么使用mask-創(chuàng)新互聯(lián)
當(dāng)前地址:http://www.dlmjj.cn/article/jchse.html