python - 使用切片/掩码而不是 for 循环来查找数组中的项目
问题描述
p= np.array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]])
我有上面的数组,需要找到可被 2 和 3 整除的项目,而无需使用 for 循环将其转换为平面数组,然后进行切片/屏蔽。
我能够弄清楚 for-loops 部分,并且遇到了切片/屏蔽部分的一些问题。
# we know that 6, 12 and 18 are divisible by 2 and 3
# therefore we can use slicing to pull those numbers out of the array
print(p[1:2,0:1]) # slice array to return 6
print(p[2:3,1:2]) # slice array to return 12
print(p[3:4,2:3]) # slice array to return 18
m=np.ma.masked_where(((p[:, :]%2==0)&(p[:, :]%3==0)),p)
print(m)
mask=np.logical_and(p%2==0,p%3==0)
print(mask)
有没有更有效的方法对数组进行切片以找到 6、12 和 18?另外,有没有办法让两个掩码函数中的任何一个只输出 6、12 和 18?第一个显示与我想要的相反,而另一个返回布尔答案。
解决方案
你几乎拥有它!
mask=np.logical_and(p%2==0,p%3==0)
给你True
在哪里p % 2 == 0 and p % 3 == 0
。
mask = array([[False, False, False, False, False],
[ True, False, False, False, False],
[False, True, False, False, False],
[False, False, True, False, False]])
由此,您可以简单地获得p
where mask
is的值True
p[mask]
这给出了输出:
array([ 6, 12, 18])
推荐阅读
- html - Angular 9 ng 模板
- google-sheets - QUERY 函数适用于示例工作表,但不适用于具有相同公式的新工作表
- laravel - 奇怪的 Laravel Mix Webpack Chunkname 与 2 个文件组合
- python-3.x - 根据索引插入无
- vue.js - VueJS:材料表:如何从行中分配一个值作为列标题?
- python - 如何将列表的 numpy 列表直接作为列附加到现有 CSV 文件?
- visual-studio-code - 如何在 vscode 中激活 neovim 的键绑定?
- javascript - 在 JavaScript 中导入带有波兰语字符的 JSON 时编码错误
- node.js - 为没有开发依赖项的 nodejs 分发创建一个 zip 文件(捆绑)
- java - JPA Criteria API - 查询代码在单独执行时有效,但在用作子查询时无效