• 技术文章 >Python技术 >Python基础教程

    Python之numpy中mask选取子集

    小P小P2020-11-04 09:35:59原创5074
    有刚入门的小白不知道numpy中如何使用mask,今天小编就来讲讲使用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)


    是不是很容易呢,小伙伴们学会了没有~更多Python学习推荐:PyThon学习网教学中心

    专题推荐:numpy中使用mask;python
    品易云
    上一篇:python语言编程题:如何求数组连续最大和 下一篇:使用python time()方法

    相关文章推荐

    • 详解Python中numpy.loadtxt()读取txt文件• Python中numpy如何生成mask图像• Python中如何使用numpy.getmask()函数• Python中numpy数组如何添加和删除元素• Python中numpy怎样按行或列提取矩阵• Python基础:numpy中空值怎样设置• Python实用之numpy中空数组的创建

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网