【问题标题】:Python: adding values to a numpy bool array column-wisePython:按列向numpy bool数组添加值
【发布时间】:2017-06-01 04:41:29
【问题描述】:

我有一个值列表和一个 numpy bool 数组,如下所示:

[[False  True  True False False  True]
 [ True  True  True False False  True]
 [ True  True  True  True  True  True]]



list = [1, 7, 2, 2, 3, 7, 1, 1, 4, 2, 9, 1, 2]

我的目标是通过列方式将 list 中的整数添加到 bool 数组中的 True 值,如果可能的话,让 false 值包含整数 0。请记住,我正在尝试遍历 bool按列排列数组,因此最终结果如下所示:

 [[0  2  7  0  0  9]
 [ 1  2  1  0  0  1]
 [ 7  3  1  4  2  2]] 

【问题讨论】:

    标签: arrays numpy boolean


    【解决方案1】:

    使用转置方法:

    import numpy as np
    boo = np.array([[False, True, True, False, False, True],
                    [True, True, True, False, False, True],
                    [True, True, True, True, True, True]])
    x = np.zeros(boo.shape, dtype=int)
    y = np.array([1, 7, 2, 2, 3, 7, 1, 1, 4, 2, 9, 1, 2])
    x.T[boo.T] = y
    print(x)
    
    [[0 2 7 0 0 9]
     [1 2 1 0 0 1]
     [7 3 1 4 2 2]]
    

    【讨论】:

    • 使用转置视图!不错。
    • 这正是我所需要的。由于某种原因,我无法弄清楚必须转置两个对象
    【解决方案2】:

    设置

    a
    Out[163]: 
    array([[False,  True,  True, False, False,  True],
           [ True,  True,  True, False, False,  True],
           [ True,  True,  True,  True,  True,  True]], dtype=bool)
    
    l
    Out[164]: [1, 7, 2, 2, 3, 7, 1, 1, 4, 2, 9, 1, 2]
    

    解决方案

    Use a list comprehension and pop function:
    np.array([l.pop(0) if e else 0 for e in a.flatten('F')]).reshape(a.shape,order='F')
    Out[177]: 
    array([[0, 2, 7, 0, 0, 9],
           [1, 2, 1, 0, 0, 1],
           [7, 3, 1, 4, 2, 2]])
    

    另一种更详细的方法:

    #flatten a to a 1D array of int type
    a2 = a.flatten('F').astype(int)
    
    #replace 1s with values from list
    a2[a2==1] = l
    
    #reshape a2 to the shape of a
    a2.reshape(a.shape,order='F')
    Out[162]: 
    array([[0, 2, 7, 0, 0, 9],
           [1, 2, 1, 0, 0, 1],
           [7, 3, 1, 4, 2, 2]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 2021-06-17
      • 2021-10-22
      • 1970-01-01
      • 2021-07-16
      • 2018-03-05
      相关资源
      最近更新 更多