Python-在3D NDARRAY和2D NDARRAY之间检查常见的涂鸦,而无需使用循环! (numpy)
我试图解决一个我得到2个布尔人的问题。 一种形状(n,m,z),表示为a,另一个表示为B。 如果我将3D阵列视为“ Z” 2D数组的数组,i] == b [x,y] == 1。
例如: 让A
np.array([[[1,0,0],
[0,1,0],
[0,0,1]]
,
[[0,1,0],
[0,1,0],
[0,1,0]],
[[1,0,0],
[0,1,0],
[0,0,1]]])
和B为:
> [[1,0,0],
[0,1,0],
[0,0,1]])
函数应返回true!
我需要在没有任何循环的情况下解决它(只有numpy工具)!
先感谢您。
Im trying to solve a problem in which I am given 2 ndarray of booleans .
one of shape (n,m,z), denote as A, and the other (n,m), denote as B.
If I am thinking of the 3D array as an array of 'z' 2D arrays, I would like to check if for every i between 0 and z, there is at least one coordinate [x,y] that: A[x,y,i] == B[x,y] == 1.
for example:
let A be
np.array([[[1,0,0],
[0,1,0],
[0,0,1]]
,
[[0,1,0],
[0,1,0],
[0,1,0]],
[[1,0,0],
[0,1,0],
[0,0,1]]])
and B be:
> [[1,0,0],
[0,1,0],
[0,0,1]])
The function should return True!
I need to solve it without any loops (just numpy tools)!
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
np.logical_and(a == 1,a == b)
为您提供每个2D行的布尔掩码。sum((1,2))
给出了每行匹配项的计数。我们不在乎是1或更多,因此我们获得> = 1
,并使用sum()
对它们进行计数。这必须等于行的数量A.形状[0]
编辑:
(1,2)
是我们想要看到的轴。如果轴为x,y,z
,则总和应通过(0,1)
而不是(1,2)
对应于x,y
,而不是y,z
。但是,数组a
表示z
这是第一个轴。You can use
np.logical_and(a == 1, a == b)
gives you the boolean mask for every 2D row.sum((1,2))
gives the count of matches in each row. We don't care if it's 1 or more so we get the>= 1
and count them usingsum()
. This must be equal to the number of rowsa.shape[0]
Edit:
(1,2)
are the axes we want to see equivalency for. In case axes arex,y,z
then the sum should be over(0,1)
instead of(1,2)
which would correspond tox,y
instead ofy,z
. However, the arraya
representation is made wherez
here is the first axis.