[英]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.