Numpy: sets one specific element of each column based on array indexing

On a smaller scale than what I need, here is an example of what I am looking for:

>>> a
array([[  21,   22,   23,   24,   25,   26,   27],
       [  56,   57,   58,   59,   60,   61,   62],
       [  14,   15,   16,   17,   18,   19,   20],
       [   7,    8,    9, 1010,   11,   12,   13],
       [  42,   43,   44,   45,   46,   47,   48],
       [  63,   64,   65,   66,   67,   68,   69],
       [   0,    1,    2,    3,    4,    5,    6],
       [  49,   50,   51,   52,   53,   54,   55],
       [  28,   29,   30,   31,   32,   33,   34],
       [  35,   36,   37,   38,   39,   40,   41]])
>>> indices = a.argmax(axis=0)
>>> indices
array([5, 5, 5, 3, 5, 5, 5])
>>> b = np.zeros(a.shape)
>>> b[indices] = 1.0
>>> b # below is the actual output, not what I want
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]])

      

But I really need:

>>> b
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]])

      

Indexing in numbers can get extremely tricky, and it's a little harder to put it in words, so hopefully someone can figure out what I'm looking for. Basically, it should set 1 wherever the column is at maximum and zero elsewhere. How can i do this?

+3


source to share


2 answers


From the docs :

If the number of objects in the selection set is less than N, then it is :

accepted for any subsequent measurements.



There is only one array in your choice, so you will get each row from indices equal to 1. To overcome this, you need the column indices. I think this would be the trick:

b[indices, np.arange(a.shape[1])] = 1.0

      

+4


source


There may be a path without a loop, but you can always:



indices = a.argmax(axis=0)
b = np.zeros(a.shape)
for j,ind in enumerate(indices):
    b[ind, j] = 1

      

0


source







All Articles