[英]How can a NumPy array of booleans be used to remove/filter rows of another NumPy array?
I have one NumPy array like this: 我有一个这样的NumPy数组:
array([[ True],
[ True],
[ True],
[False],
[False],
[False],
[False],
[False],
[False],
[False],
[False],
[False],
[False],
[False],
[False],
[False],
[False]], dtype=bool)
I want to use this array to filter the rows of another array like this: 我想使用此数组来过滤另一个数组的行,如下所示:
array([[-0.45556594, 0.46623859],
[-1.80758847, -0.08109728],
[-0.9792373 , -0.15958186],
[ 4.58101272, -0.02224513],
[-1.64387422, -0.03813 ],
[-1.8175146 , -0.07419429],
[-1.15527867, -0.1074057 ],
[-1.48261467, -0.00875623],
[ 2.23701103, 0.67834847],
[ 1.45440669, -0.62921477],
[-1.13694557, 0.07002631],
[ 1.0645533 , 0.21917462],
[-0.03102173, 0.18059074],
[-1.16885461, -0.06968157],
[-0.51789417, -0.05855351],
[ 4.23881128, -0.30072904],
[-1.37940507, -0.06478938]])
Applying the filter would result in the following array, with just the first three rows: 应用过滤器将得到以下仅前三行的数组:
array([[-0.45556594, 0.46623859],
[-1.80758847, -0.08109728],
[-0.9792373 , -0.15958186]])
How can this be done? 如何才能做到这一点? When I attempt to do something like
B[A]
, where A
is the filter array and B
is the other one, I get only the first column. 当我尝试执行类似
B[A]
,其中A
是过滤器数组,而B
是另一个数组,我只会得到第一列。
You are trying to select entire rows, so you will want a 1 dimensional array to use to select. 您正在尝试选择整个行,因此需要使用一维数组来选择。 As mentioned in comments you can use
numpy.ravel()
to straighten out your bool array and apply it to b
with: 如注释中所述,您可以使用
numpy.ravel()
来整理bool数组,并使用以下命令将其应用于b
:
b[a.ravel()]
You can also explicitly select the first column of a
and apply it to b
with: 您也可以明确选择的第一列
a
,并将其应用到b
有:
b[a[:, 0]])
Test Code: 测试代码:
a = np.array(
[[ True],
[ True],
[ True],
[False],
[False],
[False]], dtype=bool)
b = np.array(
[[-0.45556594, 0.46623859],
[-1.80758847, -0.08109728],
[-0.9792373 , -0.15958186],
[ 4.58101272, -0.02224513],
[-1.64387422, -0.03813 ],
[-1.37940507, -0.06478938]])
print(b[a.ravel()])
print(b[a[:, 0]])
Results: 结果:
[[-0.45556594 0.46623859]
[-1.80758847 -0.08109728]
[-0.9792373 -0.15958186]]
[[-0.45556594 0.46623859]
[-1.80758847 -0.08109728]
[-0.9792373 -0.15958186]]
您还可以使用np.where查找合格的行索引:
b[np.where(a)[0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.