Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of 1's in indexed positions

I currently have an array of indices of the minimum values in an array.

It looks something like this:

[[0],
 [1],
 [2],
 [1],
 [0]]

(The maximum index is 3)

What I want is an array that looks like this:

[[1, 0, 0]
 [0, 1, 0]
 [0, 0, 1]
 [0, 1, 0]
 [1, 0, 0]]

Where the 1 is in the column of the minimum.

Is there an easy way to do this in numpy?

like image 311
jgilchrist Avatar asked Dec 10 '25 10:12

jgilchrist


1 Answers

Use NumPy's broadcasting of ==:

>>> minima = np.array([[0], [1], [2], [1], [0]])
>>> minima == arange(minima.max() + 1)
array([[ True, False, False],
       [False,  True, False],
       [False, False,  True],
       [False,  True, False],
       [ True, False, False]], dtype=bool)
>>> (minima == arange(minima.max() + 1)).astype(int)
array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0],
       [1, 0, 0]])
like image 92
Fred Foo Avatar answered Dec 12 '25 01:12

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!