Python/Numpy:在2D数组中矢量化重复的行插入



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

我有一个大的2D numpy数组arr(下面(和一个indices列表。对于indicesarr的每个索引,我想在同一索引处将该索引处的行插入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', ' ', ' ']
#...
]

您可以使用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)

最新更新