【问题标题】:Numpy: set one specific element of each column based on indexing by arrayNumpy:根据数组索引设置每一列的一个特定元素
【发布时间】:2015-07-01 04:56:45
【问题描述】:

与我需要的相比,规模较小,这是我想要做的一个例子:

>>> 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,在其他地方设置为零。我该怎么做呢?

【问题讨论】:

    标签: python arrays numpy scipy


    【解决方案1】:

    来自docs

    如果选择元组中的对象数量小于 N ,则 : 假定用于任何后续维度。

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

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

    【讨论】:

    • 不错 :-) 我知道某处有单线
    • 啊哈,谢谢!我觉得我现在对 numpy 索引有了更好的理解。
    • 谢谢。我来自 MATLAB,所以这样做 0:a.shape[1] 我认为实际上会产生列索引,但这会执行切片。在 MATLAB 中,: 运算符既进行切片又生成索引向量,这就是我的麻烦所在。现在我知道我必须手动生成列索引。谢谢!
    【解决方案2】:

    可能有一种方法没有循环,但你总是可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-09
      • 2015-04-14
      • 2012-01-05
      • 1970-01-01
      • 2018-12-05
      • 2022-10-14
      • 1970-01-01
      相关资源
      最近更新 更多