Python-在3D NDARRAY和2D NDARRAY之间检查常见的涂鸦,而无需使用循环! (numpy)

发布于 2025-01-25 09:50:37 字数 520 浏览 2 评论 0原文

我试图解决一个我得到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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

平生欢 2025-02-01 09:50:37

您可以使用

(np.logical_and(a == 1, a == b).sum((1,2)) >= 1).sum() == a.shape[0]

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).sum((1,2)) >= 1).sum() == a.shape[0]

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 using sum(). This must be equal to the number of rows a.shape[0]

Edit: (1,2) are the axes we want to see equivalency for. In case axes are x,y,z then the sum should be over (0,1) instead of (1,2) which would correspond to x,y instead of y,z. However, the array a representation is made where z here is the first axis.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文