繁体   English   中英

Python/Numpy:向量化二维数组中的重复行插入

[英]Python/Numpy: Vectorizing repeated row insertion in a 2D array

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM