首页 > 解决方案 > Python/Numpy:向量化二维数组中的重复行插入

问题描述

是否可以对行的插入进行矢量化?

我有一个大型 2D numpy 数组arr(如下)和一个indices. 对于 in 的每个索引,arrindices想将该索引处的行插入arr同一索引处的行 5 次。

indices = [2, 4, 5, 9, 11, 12, 16, 18, 19]  

目前我只是遍历所有索引并插入新行。对于数千行的大型列表,这种方法很慢,所以出于性能原因,我想知道是否可以对这种多点平铺类型插入进行矢量化?

arr = [       
        [' ', ' ', 'd'],
        [' ', 'd', ' '],
        [' ', 'd', 'd'],    # <-- reinsert arr[2] here 5 times
        ['d', ' ', ' '],
        ['d', ' ', 'd'],    # <-- reinsert arr[4] here 5 times
        ['d', 'd', ' '],    # <-- reinsert arr[5] here 5 times
        ['d', 'd', 'd'],
        [' ', ' ', 'e'],
        [' ', 'e', ' '],
        [' ', 'e', 'e'],    # <-- reinsert arr[9] here 5 times
        ['e', ' ', ' '],
        ['e', ' ', 'e'],    # <-- reinsert arr[11] here 5 times
        ['e', 'e', ' '],    # <-- reinsert arr[12] here 5 times
        ['e', 'e', 'e'],
        [' ', ' ', 'f'],
        [' ', 'f', ' '],
        [' ', 'f', 'f'],    # <-- reinsert arr[16] here 5 times
        ['f', ' ', ' '],
        ['f', ' ', 'f'],    # <-- reinsert arr[18] here 5 times
        ['f', 'f', ' ']     # <-- reinsert arr[19] here 5 times
    ]

第一次插入所需结果的示例:

arr = [       
        [' ', ' ', 'd'],
        [' ', 'd', ' '],
        [' ', 'd', 'd'],    # <-- arr[2]
        [' ', 'd', 'd'],    # <-- new insert
        [' ', 'd', 'd'],    # <-- new insert
        [' ', 'd', 'd'],    # <-- new insert
        [' ', 'd', 'd'],    # <-- new insert
        [' ', 'd', 'd'],    # <-- new insert
        ['d', ' ', ' ']
        #...
      ]

标签: pythonnumpymultidimensional-arrayvectorizationmasking

解决方案


你可以用np.repeat这个:

indices = [2, 4, 5, 9, 11, 12, 16, 18, 19]
rpt = np.ones(len(arr), dtype=int)
rpt[indices] = 5

np.repeat(arr, rpt, axis=0)

推荐阅读