I have an np array with shape (50,2)
so for each row, I'm trying to get the index of the minimum value which I think I managed to roughly
for i in range(len(mylist)):
list(my_list[i]).index(min(my_list[i]))
however, I am getting a brain block on how to insert '1' at the index of the minimum value?
for e.g
([[2,4],
[5,3]])
will give the index values for the min(my_list) as
0
1
then the first row will have the index being 0 and the 2nd row will be 1
how do I insert a binary value at the index of the min value so that the output is like
[1,0]
[0,1]
.
.
.
thank you!
CodePudding user response:
Use numpy.arange
for the indices of the rows and numpy.argmin
for the indices of the columns:
import numpy as np
arr = np.array([[2, 4],
[5, 3]])
res = np.zeros_like(arr)
res[np.arange(arr.shape[0]), arr.argmin(axis=1)] = 1
print(res)
Output
[[1 0]
[0 1]]
CodePudding user response:
A more elegant and readable way to go about your problem is to first, copy your array into another one, then switch the columns in the second array and just simply use the logical operators to get what you want. Take a look at the code below:
import numpy as np
my_list = np.array([[2, 4],
[5, 3]])
my_list_swaped = my_list.copy()
my_list_swaped [ : , [0,1]] = my_list_swaped[ : ,[1,0]] #Swapping the columns
print( my_list < my_list_swaped )
What you will get is:
array([[ True, False],
[False, True]])
which is basically:
array([[ 1, 0],
[0, 1]])
Simplifying the code:
If you don't have a problem doing it the dirty way (less readable way), you can directly use the logical operator along with indexing to get what you want:
import numpy as np
my_list = np.array([[2, 4],
[5, 3]])
result = my_list < my_list[ : , [1,0] ]
print(result)