在给定的数组中,我想用另一个数组(不包含重复项)中该值的索引替换这些值。这是我正在尝试做的一个简单示例:
import numpy as np
from copy import deepcopy
a = np.array([[0, 1, 2], [2, 1, 3], [0, 1, 3]])
chg = np.array([3, 0, 2, 1])
b = deepcopy(a)
for new, old in enumerate(chg):
b[a == old] = new
print b
# [[1 3 2] [2 3 0] [1 3 0]]
但我需要在大型数组上执行此操作,因此就执行时间而言,使用显式循环是 Not Acceptable 。
我不知道如何使用花哨的 numpy 函数来做到这一点......
最佳答案
take
是你的 friend 。
a = np.array([[0, 1, 2], [2, 1, 3], [0, 1, 3]])
chg = np.array([3, 0, 2, 1])
inverse_chg=chg.take(chg)
print(inverse_chg.take(a))
给出:
[[1 3 2]
[2 3 0]
[1 3 0]]
或者更直接地使用花式索引:chg[chg][a]
,但是 inverse_chg.take(a)
快三倍。
关于python - 用列表中的索引替换数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33348939/