Roma  Karageorgievich Roma Karageorgievich - 3 months ago 10
Python Question

Find indexes of two lists

I have two numpy lists:

x = ['A', 'A', 'C', 'A', 'V', 'A', 'B', 'A', 'A', 'A']


y = ['1', '2', '1', '1', '3', '2', '1', '1', '1', '1']


How can I find indexes when simulataneously
x
equals
'A'
and
y
equals
'2'
?

I expect to get indexes [1, 5].

I tried to use:
np.where(x == 'A' and y == '2')
but it didn't help me.

Answer

You need to convert the list to numpy array in order to use vectorized operation such as == and &:

import numpy as np
np.where((np.array(x) == "A") & (np.array(y) == "2"))
# (array([1, 5]),)

Shorter version (if you are sure that x and y are numpy arrays):

>>> np.where(np.logical_and(x == 'A', y == '2'))
(array([1, 5]),)