Simple question, I want to get a 1D numpy array.
Given a 2D array where each row contains a single '1' value, how can it be converted to a 1D array, consisting of the column index of the '1' in the 2D array
[[ 0. 0. 1.]
[ 0. 0. 1.]
[ 0. 0. 1.]
[ 0. 1. 0.]
[ 0. 1. 0.]
[ 0. 1. 0.]
[ 0. 1. 0.]
[ 1. 0. 0.]]
to
[2 2 1 1 1 1 0]
How would I do it in python? I don't know the terminology for it, do let me know the proper terms for such transformation.
You are looking for the index with the maximum value along the first axis:
>>> a.argmax(axis=1)
array([2, 2, 2, 1, 1, 1, 1, 0])
a.argmax(axis=None, out=None)Return indices of the maximum values along the given axis.
If the other values are not necessarily less than one, filter for 1 first.
This gives an array of True and False values. Now, use argmax():
>>> (a == 1).argmax(axis=1)
array([2, 2, 2, 1, 1, 1, 1, 0])
True acts like a 1 and False like a 0, because bool inherits from int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With