Reputation: 43
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?
Upvotes: 3
Views: 71
Reputation: 117345
for lists you could do
>>> a = [[0], [1], [2], [1], [0]]
>>> N = 3
>>> [[1 if x[0] == i else 0 for i in range(N)] for x in a]
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]]
Upvotes: 0
Reputation: 363517
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]])
Upvotes: 6