Reputation: 95
In a boolean array, I am trying to obtain the column index of the first True. argmax works with at least one True, but understandably max(False) is 0. I'm wondering what the best method would be, given a very large array.
name = np.array(['a', 'b', 'c', 'd'])
boolarr = np.array([[True, False, False, True],
[False, False, True, True],
[False, False, False, False]])
colidx = np.argmax(boolarr,axis=1)
print(name[colidx]) #result: ['a', 'c', 'a'] desired: ['a', 'c', None]
Upvotes: 5
Views: 162
Reputation: 51155
You can't change the behavior of argmax
, since the maximum of a row with all False
is 0. However, you can use any
to determine the rows that contain all False
, and use np.where
to mask your result:
out = name[colidx]
np.where(boolarr.any(1), out, None)
array(['a', 'c', None], dtype=object)
Upvotes: 3