如何与真实值相交布尔子阵列?

发布于 2025-02-04 21:58:18 字数 843 浏览 2 评论 0原文

我知道numpy提供 使我们能够仅将两个布尔数阵列与真实值相交(真实和true将产生真实和false会产生false)。 但是,

a = np.array([True, False, False,  True, False], dtype=bool)
b = np.array([False,  True,  True,  True,  False], dtype=bool)

np.logical_and(a, b)
> array([False, False, False, True, False], dtype=bool)

我想知道如何将其应用于整个数组中的两个子阵列?例如,考虑数组:

[[[ True,  True], [ True, False]], [[ True, False], [False,  True]]]

我想要相交的两个子阵列是:

[[ True,  True], [ True, False]]

哪个

[[ True, False], [False,  True]]

应该产生:

[[ True, False], [False,  False]]

有没有办法指定我要在最外面的子阵列中应用逻辑_和()以结合两个?

I know that Numpy provides logical_and() which allows us to intersect two boolean arrays for True values only (True and True would yield True while True and False would yield False). For example,

a = np.array([True, False, False,  True, False], dtype=bool)
b = np.array([False,  True,  True,  True,  False], dtype=bool)

np.logical_and(a, b)
> array([False, False, False, True, False], dtype=bool)

However, I'm wondering how I can apply this to two subarrays in an overall array? For example, consider the array:

[[[ True,  True], [ True, False]], [[ True, False], [False,  True]]]

The two subarrays I'm looking to intersect are:

[[ True,  True], [ True, False]]

and

[[ True, False], [False,  True]]

which should yield:

[[ True, False], [False,  False]]

Is there a way to specify that I want to apply logical_and() to the outermost subarrays to combine the two?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

吃颗糖壮壮胆 2025-02-11 21:58:18

您可以使用 .REDUCE() 沿着第一个轴:

>>> a = np.array([[[ True,  True], [ True, False]], [[ True, False], [False,  True]]])
>>> np.logical_and.reduce(a, axis=0)

array([[ True, False],
       [False, False]])

即使您的外部阵列中有两个以上的“子阵列”,这也可以。我更喜欢这种方法,而不是解开包装方法,因为它允许您在上应用您的功能(np.logical_and)。

You can use .reduce() along the first axis:

>>> a = np.array([[[ True,  True], [ True, False]], [[ True, False], [False,  True]]])
>>> np.logical_and.reduce(a, axis=0)

array([[ True, False],
       [False, False]])

This works even when you have more than two "sub-arrays" in your outer array. I prefer this over the unpacking approach because it allows you to apply your function (np.logical_and) over any axis of your array.

小女人ら 2025-02-11 21:58:18

如果我正确理解您的问题,您正在寻找:

import numpy as np

output = np.logical_and(a[:, 0], a[:, 1])

这只是切成阵列,以便您可以使用Logical_和结果建议的方式。

If I understand your question correctly, you are looking to do:

import numpy as np

output = np.logical_and(a[:, 0], a[:, 1])

This simply slices your arrays so that you can use logical_and the way your results suggest.

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