簡體   English   中英

替換 NumPy 數組的某些給定索引的最有效方法是什么?

[英]What's the most efficient way to replace some given indices of a NumPy array?

我有三個 arrays、 indicesvaluesreplace_values 我必須遍歷indices ,用new_values[i]替換old_values[indices[i]]中的每個值。 最快的方法是什么? 感覺應該有某種方法可以使用 NumPy 函數或高級切片而不是正常for循環來加速它。

此代碼有效,但相對較慢:

import numpy as np

# Example indices and values
values = np.zeros([5, 5, 3]).astype(int)

indices = np.array([[0,0], [1,0], [1,3]])
replace_values = np.array([[140, 150, 160], [20, 30, 40], [100, 110, 120]])

print("The old values are:")
print(values)

for i in range(len(indices)):
    values[indices[i][0], indices[i][1]] = replace_values[i]

print("The new values are:")
print(values)

使用zip分隔xy索引,然后轉換為tuple並分配:

>>> values[tuple(zip(*indices))] = replace_values
>>> values

array([[[140, 150, 160],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[ 20,  30,  40],
        [  0,   0,   0],
        [  0,   0,   0],
        [100, 110, 120],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]]])

其中tuple(zip(*indices))返回:

((0, 1, 1), (0, 0, 3))

正如@MadPhysicist 所指出的,由於您的索引本身就是np.array ,因此您可以刪除zip並使用轉置:

>>> values[tuple(*indices.T)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM