[英]NumPy 2D array boolean indexing with each axis
I created 2D array and I did boolean indexing with 2 bool index arrays.我创建了 2D 数组,并使用 2 个 bool 索引数组进行了布尔索引。 first one is for axis 0, next one is for axis 1.
第一个用于轴 0,下一个用于轴 1。
I expected that values on cross True and True from each axis are selected like Pandas.我希望像 Pandas 一样选择每个轴上的 True 和 True 交叉值。 but the result is not.
但结果不是。
I wonder how it works that code below.我想知道下面的代码是如何工作的。 and I want to get the link from official numpy site describing this question.
我想从官方 numpy 站点获取描述此问题的链接。
Thanks in advance.提前致谢。
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])
My expectation is [0, 6, 2, 8]
.我的期望是
[0, 6, 2, 8]
。 (I know how to get the result that I expect.) (我知道如何得到我期望的结果。)
In [20]: a = np.arange(9).reshape(3,3)
If the lists are passed to ix_
, the result is 2 arrays that can be used, with broadcasting
to index the desired block:如果将列表传递给
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]])
This isn't 1d, but can be easily raveled.这不是 1d,但很容易弄乱。
Trying to make equivalent boolean arrays does not work:尝试制作等效的布尔数组不起作用:
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
Boolean indexes must be either 1d, or nd matching the target, here (3,3).布尔索引必须是 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]])
What you want is consecutive slices: a[[True, False, True]][:,[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')
output: array([0, 6, 2, 8])
输出:
array([0, 6, 2, 8])
NB.注意。 this requires arrays for slicing
这需要用于切片的数组
a = np.arange(9).reshape(3,3)
x = np.array([False, False, True])
y = np.array([True, False, True])
a.T[x&y[:,None]]
output: array([0, 6, 2, 8])
输出:
array([0, 6, 2, 8])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.