[英]Numpy - Indexing with Boolean array
我有一个形状(6,5)的numpy数组,并且我试图用布尔数组索引它。 我沿着列对布尔数组进行切片,然后使用该切片对原始数组进行索引,一切都很好,但是,只要我沿行执行相同的操作,就会得到以下错误。 下面是我的代码,
array([[73, 20, 49, 56, 64],
[18, 66, 64, 45, 67],
[27, 83, 71, 85, 61],
[78, 74, 38, 42, 17],
[26, 18, 71, 27, 29],
[41, 16, 17, 24, 75]])
bool = a > 50
bool
array([[ True, False, False, True, True],
[False, True, True, False, True],
[False, True, True, True, True],
[ True, True, False, False, False],
[False, False, True, False, False],
[False, False, False, False, True]], dtype=bool)
cols = bool[:,3] # returns values from 3rd column for every row
cols
array([ True, False, True, False, False, False], dtype=bool)
a[cols]
array([[73, 20, 49, 56, 64],
[27, 83, 71, 85, 61]])
rows = bool[3,] # returns 3rd row for every column
rows
array([ True, True, False, False, False], dtype=bool)
a[rows]
IndexError Traceback (most recent call last)
<ipython-input-24-5a0658ebcfdb> in <module>()
----> 1 a[rows]
IndexError: boolean index did not match indexed array along dimension 0; dimension is 6 but corresponding boolean dimension is 5
由于rows
中只有5个条目,
In [18]: rows
Out[18]: array([ True, True, False, False, False], dtype=bool)
由于长度不匹配,它无法索引数组中的6
行。
In [20]: arr.shape
Out[20]: (6, 5)
In [21]: rows.shape
Out[21]: (5,)
当您索引到像arr[rows]
这样的数组时,由于rows
是一维数组,因此它将被解释为您正在索引到轴0。 因此,必须对轴0使用:
,对轴1使用rows
,如:
# select all rows but only columns where rows is `True`
In [19]: arr[:, rows]
Out[19]:
array([[73, 20],
[18, 66],
[27, 83],
[78, 74],
[26, 18],
[41, 16]])
另外,请不要将bool
用作变量名,因为它是内置关键字。 这可能会在以后的代码中引起意外的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.