Leigh
Leigh

Reputation: 49

Indexing values in a 2D array in python

This shouldn't be that hard. Assume I have a 2D array:

a = [['1' 'George']
     ['5' ' ']
     ['7' 'Jose']
     ['5' ' ']
     ['7','Fred']]

I wish to find all the indexed values where a[:,1] == ' '

My best guess is:

missing_vals = a[a[:,' ']==' '
a[missing_vals] 

I don't want the answer:

   ['5','5'] 

but the answer:

[1,4]

Meaning the 2nd and 5th elements of the array.

Thanks.

Upvotes: 0

Views: 38

Answers (1)

Ray Toal
Ray Toal

Reputation: 88378

This is what you are looking for:

>>> a = [['1', 'George'],
...       ['5', ' '],
...       ['7', 'Jose'],
...       ['5', ' '],
...       ['7','Fred']]
>>> [i for i, [k,v] in enumerate(a) if v == ' ']
[1, 3]

Explanation:

We are asking for all indexes i in list a at which the element [k,v] in a has the element v equal to a space.

Upvotes: 1

Related Questions