numpy:根据数组索引为每一列设置一个特定元素 [英] Numpy: set one specific element of each column based on indexing by array

查看:66
本文介绍了numpy:根据数组索引为每一列设置一个特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与我所需要的相比,这是一个较小的规模,这是我要做的事的一个示例:

On a smaller scale compared to what I need, here's an example of what I'm looking to do:

>>> 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.]])

但是我真正需要的是:

>>> 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.]])

Numpy索引会变得非常复杂,并且很难用语言表达出来,因此希望有人能够理解我在寻找什么.从本质上讲,只要列的最大值为1,其他位置为零即可设置为1.我将如何去做?

Numpy indexing can get extremely complicated and it's a little difficult to put the above into words, so hopefully someone can understand what I'm looking for. Essentially it's to set a 1 wherever there's a max of a column and zero elsewhere. How would I go about doing this?

推荐答案

来自

如果选择元组中的对象数小于N,则任何后续尺寸均假定为:.

在选择中只有一个数组,因此从索引中获得的每一行都等于1.要克服这一点,您需要列索引.我想这可以解决问题:

In your selection there only one array, so you get every row from indices to be equal to 1. To overcome that, you need column indices. I guess this will do the trick:

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

这篇关于numpy:根据数组索引为每一列设置一个特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆