在给定的数组中,我想用另一个数组中的该值的索引替换这些值(不包含重复项)。这是我尝试做的一个简单示例:
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]]
但是我需要在大型数组上执行此操作,因此就执行时间而言,显式循环是不可接受的。
我不知道如何使用花哨的numpy函数来做到这一点...
take
是你的朋友。
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)
速度要快三倍。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句