python - Python/Numpy:向量化二维数组中的重复行插入
问题描述
是否可以对行的插入进行矢量化?
我有一个大型 2D numpy 数组arr
(如下)和一个indices
. 对于 in 的每个索引,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)
推荐阅读
- ios - 如何启用 Xcode 调试消息
- swift - 如何在 ImageView 中获取图像的路径
- java - 致命错误编译:无法运行 ecj 编译器:无法识别的选项:--module-version
- gradle - Gradle 外部化配置
- java - 传递方法参考 NoClassDefFoundError
- c++ - 如何用向量将 C++ 函数包装在 C 中
输出参数? - c - 隐式类型转换的意外结果
- python - 如何捕获 Python 中的嵌套函数调用已经捕获的异常
- vba - 如何使用 VBA 将查询结果从子窗体传递到报表?
- python - ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败 (_ssl.c:852)