繁体   English   中英

每个轴的 NumPy 2D 数组布尔索引

[英]NumPy 2D array boolean indexing with each axis

我创建了 2D 数组,并使用 2 个 bool 索引数组进行了布尔索引。 第一个用于轴 0,下一个用于轴 1。

我希望像 Pandas 一样选择每个轴上的 True 和 True 交叉值。 但结果不是。

我想知道下面的代码是如何工作的。 我想从官方 numpy 站点获取描述此问题的链接。

提前致谢。

a = np.arange(9).reshape(3,3)
a
----------------------------
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
a[ [True, False, True], [True, False, True] ]
--------------------------
array([0, 8])

我的期望是[0, 6, 2, 8] (我知道如何得到我期望的结果。)

In [20]: a = np.arange(9).reshape(3,3)

如果将列表传递给ix_ ,则结果是 2 个可以使用的数组,并通过broadcasting来索引所需的块:

In [21]: np.ix_([True, False, True], [True, False, True] )
Out[21]: 
(array([[0],
        [2]]),
 array([[0, 2]]))
In [22]: a[_]
Out[22]: 
array([[0, 2],
       [6, 8]])

这不是 1d,但很容易弄乱。

尝试制作等效的布尔数组不起作用:

In [23]: a[[[True], [False], [True]], [True, False, True]]
Traceback (most recent call last):
  File "<ipython-input-23-26bc93cfc53a>", line 1, in <module>
    a[[[True], [False], [True]], [True, False, True]]
IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

布尔索引必须是 1d 或 nd 匹配目标,这里是 (3,3)。

In [26]: np.array([True, False, True])[:,None]& np.array([True, False, True])
Out[26]: 
array([[ True, False,  True],
       [False, False, False],
       [ True, False,  True]])

你想要的是连续的切片: a[[True, False, True]][:,[True, False, True]]

a = np.arange(9).reshape(3,3)
x = [True, False, True]
y = [True, False, True]
a[x][:,y]

作为平面阵列

a[[True, False, True]][:,[True, False, True]].flatten(order='F')

输出: array([0, 6, 2, 8])

选择

注意。 这需要用于切片的数组

a = np.arange(9).reshape(3,3)
x = np.array([False, False, True])
y = np.array([True, False, True])
a.T[x&y[:,None]]

输出: array([0, 6, 2, 8])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM