Python/Numpy:矢量化2D数组中重复的行插入 [英] Python/Numpy: Vectorizing repeated row insertion in a 2D array

查看:60
本文介绍了Python/Numpy:矢量化2D数组中重复的行插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以向量化行的插入?

Is it possible to vectorize the insertion of rows?

我有一个大型2D numpy数组 arr (如下)和 indices 的列表.对于 indices arr 的每个索引,我想将该索引处的行插入到同一索引处的 arr 行中5次./p>

I have a large 2D numpy array arr (below) and a list of indices. For each index of arr in indices I would like to insert the row at that index back into arr row 5 times at that same index.

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

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

Currently I'm just looping through all the indices and inserting new rows. This approach is slow for a large list of thousands of rows, so for performance reasons I'm wondering is it possible to vectorize this multi-point tile-type insertion?

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
    ]

首次插入所需结果的示例:

Example of first insertion of desired result:

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)

这篇关于Python/Numpy:矢量化2D数组中重复的行插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆