Numpy中的mask的使用

夏夜,天上缀满了闪闪发光的星星,像细碎的流沙铺成的银河斜躺在青色的天宇上。大地已经沉睡了。我任了性,纵容思念开成一片海,定格成回忆里抹不去的风景。太阳把大海映红了,好像得大海披上了一层红纱。

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矩阵内某条件的行置换为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)

本文Numpy中的mask的使用到此结束。人生那么短,为什么要让不重要的人,影响自我重要的心境。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
python numpy中array与pandas的DataFrame转换方式

NumPy索引与切片的用法示例总结

Python多进程共享numpy 数组的方法

NumPy实现多维数组中的线性代数

解决pycharm导入numpy包的和使用时报错:RuntimeError: The current Numpy installation (‘D:\\python3.6\\lib\\site-packa的问题