【问题标题】:Numpy assign an array value based on the values of another array with column selected based on a vectorNumpy 根据另一个数组的值分配一个数组值,其中列是基于向量选择的
【发布时间】:2019-05-21 09:18:28
【问题描述】:

我有一个二维数组

X
array([[2, 3, 3, 3],
       [3, 2, 1, 3],
       [2, 3, 1, 2],
       [2, 2, 3, 1]])

和一个一维数组

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

对于 X 的每一行,我想找到 X 具有最小值且 y 的值为 1 的列索引,并将第三个矩阵中的相应行列对设置为 1

例如,在X的第一行的情况下,与最小X值(仅针对第一行)和y = 1对应的列索引为0,那么我想要Z[0,0] = 1和所有其他 Z[0,i] = 0。 同样,对于第二行,列索引 0 或 3 给出 y = 1 的最低 X 值。然后我想要 Z[1,0] 或 Z[1,3] = 1(最好 Z[1,0] = 1 和所有其他 Z[1,i] = 0,因为 0 列是第一次出现)

我的最终 Z 数组看起来像

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

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    一种方法是使用掩码数组。

    import numpy as np
    
    X = np.array([[2, 3, 3, 3],
                  [3, 2, 1, 3],
                  [2, 3, 1, 2],
                  [2, 2, 3, 1]])
    
    y = np.array([1, 0, 0, 1])
    #get a mask in the shape of X. (True for places to ignore.)
    y_mask = np.vstack([y == 0] * len(X))
    
    X_masked = np.ma.masked_array(X, y_mask)
    
    out = np.zeros_like(X)
    
    mins = np.argmin(X_masked, axis=0)
    #Output: array([0, 0, 0, 3], dtype=int64)
    
    #Now just set the indexes to 1 on the minimum for each axis.
    out[np.arange(len(out)), mins] = 1
    
    print(out)
    [[1 0 0 0]
     [1 0 0 0]
     [1 0 0 0]
     [0 0 0 1]]
    

    【讨论】:

      【解决方案2】:

      您可以使用numpy.argmin(),获取X 每一行的最小值的索引。例如:

      import numpy as np
      a = np.arange(6).reshape(2,3) + 10
      ids = np.argmin(a, axis=1)
      

      同样,您可以通过numpy.nonzeronumpy.where 来索引y 为1 的索引。 一旦你有了两个索引数组,设置第三个数组中的值应该很容易。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        • 2022-11-07
        • 2017-11-13
        • 1970-01-01
        • 2017-07-06
        • 2020-12-05
        相关资源
        最近更新 更多