鱼C论坛

 找回密码
 立即注册
查看: 2872|回复: 0

[技术交流] Python常见问题:numpy中mask的基础问题

[复制链接]
发表于 2020-11-3 15:38:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
有刚入门的小白不知道numpy中如何使用mask,今天小编就来讲讲使用mask会遇到的一些问题。
numpy中矩阵选取子集或者以条件选取子集,用mask是一种很好的方法。
简单来说就是用bool类型的indice矩阵去选择。
  1. <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">mask = np.ones(X.shape[0], dtype=bool)

  2. X[mask].shape

  3. mask.shape

  4. mask[indices[0]] = False

  5. mask.shape

  6. X[mask].shape

  7. X[~mask].shape

  8. (678, 2)

  9. (678,)

  10. (678,)

  11. (675, 2)

  12. (3, 2)<br></span></p>
复制代码


例如我们这里用来选取全部点中KNN选取的点以及所有剩余的点。
  1. <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">from sklearn.neighbors import NearestNeighbors

  2. nbrs = NearestNeighbors(10).fit(X)

  3. _,indices = nbrs.kneighbors(X)

  4. mask = np.ones(X.shape[0], dtype=bool)

  5. mask[indices[0]] = False

  6. plt.scatter(X[mask][:,0],X[mask][:,1],c='g')

  7. plt.scatter(X[~mask][:,0],X[~mask][:,1],c='r')<br></span></p>
复制代码


带条件选择替换,比如我们需要将a矩阵内某条件的行置换为888剩余置换为999,可以直接用mask或者再用where一步搞定:
  1. <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool)

  2. mask[indices] = False

  3. a[~mask] = 999

  4. a[mask] = 888

  5. #############

  6. np.where(mask, 888, 999)<br></span></p>
复制代码

是不是很容易呢,小伙伴们学会了没有~更多Python学习推荐:PyThon学习网教学中心。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-29 05:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表