numpy数组上的2D argmax

时间:2021-09-18 13:26:45

Starting with a numpy array v:

从numpy数组v开始:

v = \
np.array([[0, 0, 0, 0, 0],
          [0, 0, 1, 0, 0],
          [1, 0, 0, 0, 0],
          [0, 1, 0, 0, 0],
          [0, 0, 1, 0, 1],
          [0, 0, 0, 0, 1],
          [0, 0, 0, 1, 1]])

I want to find the first non-zero value in each column and multiply those values by 100.

我想在每列中找到第一个非零值,并将这些值乘以100。

My desired result is:

我想要的结果是:

array([[  0,   0,   0,   0,   0],
       [  0,   0, 100,   0,   0],
       [100,   0,   0,   0,   0],
       [  0, 100,   0,   0,   0],
       [  0,   0,   1,   0, 100],
       [  0,   0,   0,   0,   1],
       [  0,   0,   0, 100,   1]])

I thought to approach this problem by taking the argmax along each axis:

我想通过沿每个轴取argmax来解决这个问题:

i = v.argmax(0)
j = v.argmax(1)
v[i, j] *= 100  

I know I'm not using i and j correctly, so how can I fix this?

我知道我没有正确使用i和j,所以我该如何解决这个问题呢?

1 个解决方案

#1


3  

You just want to range through the columns

你只想要通过列范围

v[v.argmax(axis=0), np.arange(v.shape[1])] *= 100

#1


3  

You just want to range through the columns

你只想要通过列范围

v[v.argmax(axis=0), np.arange(v.shape[1])] *= 100