Python array indexing list

I want to do array indexing. I expected the result to be [0,1,1,0], however I just get an error message. How can I do this type of indexing?

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()

At the top, I actually wanted to say [False, True, True, False] not [0,1,1,0], since I want bools, so I can do the indexing

+1
source share
2 answers

First of all, you cannot use [0,1,1,0]for indexing here, therefore you are using the wrong term.

>>> 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, , .

>>> 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__ (['b', 'c']), Python PyObject_RichCompareBool, a_np_array. PyObject_RichCompareBool , , , , id(), , 1 , 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 , True False ( PyBool_Check Py_True), , PyObject_IsTrue, , , __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()

:

+1

:

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

, int(True) == 1 int(False) == 0

+2

Source: https://habr.com/ru/post/1617204/


All Articles