首页 > 解决方案 > 使用切片/掩码而不是 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?第一个显示与我想要的相反,而另一个返回布尔答案。

标签: pythonarraysnumpy

解决方案


你几乎拥有它!

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]])

由此,您可以简单地获得pwhere maskis的值True

p[mask]

这给出了输出:

array([ 6, 12, 18])

推荐阅读