Skip to main content
 首页 » 编程设计

python之使用 bool 数组的 Numpy 索引

2025年05月04日15sxdcgaq8080

我有以下数组,指示是否要拿某个项目:

import numpy as np 
 
test_array = np.array([[0, 0, 1], 
                       [1, 1, 0], 
                       [1, 1, 1]]) 

我要索引的数组是这个:

classes = ['a', 'b', 'c'] 

结果应该是这样的:

[['c'], ['a', 'b'], ['a', 'b', 'c']] 

如何做到这一点?

请您参考如下方法:

到目前为止,我看到的答案有的尴尬,有的坦率地说,令人费解,所以这里有一个简单的解决方案。

import np 
 
arr = np.array([[0, 0, 1], [1, 1, 0], [1, 1, 1]]) 
 
arr_bools = arr.astype(np.bool) 
 
lookup_lst = np.array(['a', 'b', 'c']) 
 
res = [lookup_lst[row].tolist() for row in arr_bools]