Numpy中的mask的使用

yipeiwu_com6年前Python基础

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中的反斜杠问题深入讲解

前言 python本身使用 \ 来转义一些特殊字符,比如在字符串中加入引号的时候 s = 'i\'m superman' print(s) # i'm superman 为了防止和...

python实用代码片段收集贴

获取一个类的所有子类 复制代码 代码如下: def itersubclasses(cls, _seen=None):     """Generator ov...

PyQt5每天必学之创建窗口居中效果

PyQt5每天必学之创建窗口居中效果

本文实例为大家分享了PyQt5如何能够创建在桌面屏幕上居中窗口的具体代码,供大家参考,具体内容如下 下面的脚本说明我们如何能够创建在桌面屏幕上居中的窗口。 #!/usr/bin/py...

pytorch+lstm实现的pos示例

学了几天终于大概明白pytorch怎么用了 这个是直接搬运的官方文档的代码 之后会自己试着实现其他nlp的任务 # Author: Robert Guthrie import to...

Python语言生成水仙花数代码示例

Python语言生成水仙花数代码示例

水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。 本文将通过Python代码实现打印水仙花数,具体如下: #水仙花数 #narcissist...