• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python之numpy中mask选取子集

python 搞java代码 3年前 (2022-05-21) 29次浏览 已收录 0个评论

有刚入门的小白不知道numpy中如何使用mask,今天小编就来讲讲使用mask会遇到的一些问题。


numpy中矩阵选取子集或者以条件选取子集,用mask是一种很好的方法。

简单来说就是用bool类型indice矩阵去选择。


<p style="line-height: 1.75em"><span>mask = np.ones(X.<a href="https://www.gaodaima.com/tag/shape" title="查看更多关于shape的文章" target="_blank">shape</a>[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)<br></span></p>

www#gaodaima.com来源gaodai#ma#com搞*代#码网搞代码


例如我们这里用来选取全部点中KNN选取的点以及所有剩余的点。


<p style="line-height: 1.75em"><span>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')<br></span></p>


带条件选择替换,比如我们需要将a矩阵内某条件的行置换为888剩余置换为999,可以直接用mask或者再用where一步搞定:


<p style="line-height: 1.75em"><span>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)<br></span></p>


是不是很容易呢,小伙伴们学会了没有~更多Python学习推荐:云海天Python教程网

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python之numpy中mask选取子集
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址