python - 检查 numpy 数组是否在另一个 numpy 数组中并创建一个掩码
问题描述
给定 numpy 数组
a = [[[0 0] [1 0] [2 0]]
[[0 1] [1 1] [2 1]]
[[0 2] [1 2] [2 2]]]
和列表 b
b = [[1, 0], [2, 0]]
我怎样才能得到面具c
c = [[False True True]
[False False False]
[False False False]]
解决方案
您可以使用 numpy 广播功能将 b 中的每个数字对与 b 上的所有数字对进行比较,如下所示
## np.newaxis add a new dimension at that position. missing dimension (i.e
## dimension with size 1) will repeat to match size of corresponding dimension
a = np.asarray([[[0, 0], [1, 0], [2, 0]],
[[0, 1], [1, 1], [2, 1]],
[[0, 2], [1, 2], [2, 2]]])[:,:,np.newaxis,:]
b = np.array([[1, 0], [2, 0]])[np.newaxis,:,:]
(a == b).all(axis=3).any(axis=2)
结果
array([[False, True, True],
[False, False, False],
[False, False, False]])
推荐阅读
- javascript - 排序元素vanila js
- google-app-maker - 在哪里可以找到 Google 应用制造商个人版?
- java - 我为指数编写的这个基本程序只适用于整数——我做错了什么?
- arrays - 使用 Delphi XE8 数组初始化的 WSDL
- php - 如何使用 Laravel 在 consoletvs 图表中传递值
- android - 用于安卓的 FFmpeg 包装器
- jquery - 上一行没有使用 jquery 从附加行计算/更新
- batch-file - 在批处理文件中的“start /b”之后使用 && 链接命令
- html - 覆盖的 div 高于包含的 div。如何用 CSS 修复?
- javascript - 如何测试变量是 Map 还是 Array 类型?