【问题标题】:Get the list of all possible numpy array column deletions获取所有可能的 numpy 数组列删除的列表
【发布时间】:2021-02-21 18:16:42
【问题描述】:

给定以下 numpy 数组:

>>> a = np.arange(9).reshape((3, 3))
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

如何获取所有可能删除的列的列表?所以在这种情况下:

array([[[1, 2],
        [4, 5],
        [7, 8]],

       [[0, 2],
        [3, 5],
        [6, 8]],

       [[0, 1],
        [3, 4],
        [6, 7]]])

【问题讨论】:

    标签: python numpy numpy-ndarray numpy-slicing


    【解决方案1】:

    你可以使用itertools.combinations:

    >>> from itertools import combinations
    >>> np.array([a[:, list(comb)] for comb in combinations(range(a.shape[1]), r=2)])
    
    array([[[0, 1],
            [3, 4],
            [6, 7]],
    
           [[0, 2],
            [3, 5],
            [6, 8]],
    
           [[1, 2],
            [4, 5],
            [7, 8]]])
    

    【讨论】:

    • 我正在寻找一种 numpy 索引方法,但如果没有其他问题,我会接受这个答案
    【解决方案2】:

    或者,您可以先创建所需列索引的列表,然后使用integer array indexing 从原始数组中提取所需列:

    r = range(a.shape[1])
    cols = [[j for j in r if i != j] for i in r]  
    
    cols
    # [[1, 2], [0, 2], [0, 1]]
    
    a[:, cols].swapaxes(0, 1)
    
    #[[[1 2]
    #  [4 5]
    #  [7 8]]
    #
    # [[0 2]
    #  [3 5]
    #  [6 8]]
    #
    # [[0 1]
    #  [3 4]
    #  [6 7]]]
    

    【讨论】:

      猜你喜欢
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多