python列表中的数组索引列表

python array indexing list in list

我想做数组索引。我本以为结果是 [0,1,1,0],但我只是得到一个错误。我怎样才能做这种类型的索引?

a_np_array=np.array(['a','b','c','d'])
print a_np_array in ['b', 'c']

Traceback (most recent call last):
File "dfutmgmt_alpha_osis.py", line 130, in <module>
print a_np_array in ['b', 'c']
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

在上面,我实际上是想说 [False,True,True,False] 而不是 [0,1,1,0] 因为我想要布尔值所以我可以进行索引

试试这个 list comprehension:

>>> print [int(x in ['b', 'c']) for x in a_np_array]
[0, 1, 1, 0]

利用 int(True) == 1int(False) == 0

首先你不能在这里使用 [0,1,1,0] 作为索引,所以你使用了错误的术语。

>>> a_np_array[[0,1,1,0]]  # Not useful at all
array(['a', 'b', 'b', 'a'], 
      dtype='|S1')

如果我理解正确的话,您只是想检查 a_np_array 的项目是否存在于 ['b', 'c'] 中,用于 numpy.in1d,但是 returns布尔数组我们只需要将它转换为整数数组。

>>> np.in1d(a_np_array, ['b','c'])
array([False,  True,  True, False], dtype=bool)
>>> np.in1d(a_np_array, ['b','c']).astype(int)
array([0, 1, 1, 0])

为什么 a_np_array in ['b', 'c'] 不起作用?

此处 in 运算符将对它们调用 __contains__ method of the list object(['b', 'c']) and then for each object in list Python will use the method PyObject_RichCompareBool to compare each item to a_np_array. PyObject_RichCompareBool first of all simply checks if the items to be compared are the same object, i.e same id(), if yes return 1 right away otherwise call PyObject_RichCompare。因此这将起作用:

>>> a_np_array in [a_np_array, 'c', 'a']
True

但这不会:

>>> a_np_array in [a_np_array.copy(), 'c', 'a']
Traceback (most recent call last):
  File "<ipython-input-405-dfe2729bd10b>", line 1, in <module>
    a_np_array in [a_np_array.copy(), 'c', 'a']
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

现在Python将检查PyObject_RichCompare返回的对象是否已经是布尔类型,即TrueFalse(这是使用[=43=完成的) ] 检查对象是否可以被认为是真实对象,这是通过调用对象的 __nonzero__ 方法来完成的。对于 NumPy 数组,这将最终调用返回对象的 bool()引发错误。在这里,NumPy 希望您调用 all()any() 来检查所有项目是 True 还是至少一个

>>> bool(a_np_array == 'a')
Traceback (most recent call last):
  File "<ipython-input-403-b7ced85c4f02>", line 1, in <module>
    bool(a_np_array == 'a')
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

源代码链接: