簡體   English   中英

numpy-用布爾數組索引

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM