python - 用列表中的索引替换数组中的值

标签 python arrays numpy

在给定的数组中,我想用另一个数组(不包含重复项)中该值的索引替换这些值。这是我正在尝试做的一个简单示例:

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/

相关文章:

python - 检查配置以确保每个规则都是唯一的更好方法

c - 如何正确地将数组作为函数参数传递?

python - 我可以阻止 numpy.array 将元素转换为 numpy 数组吗?

python - 尝试将 python 函数转换为 haskell 时,haskell 出现无限类型错误。为什么?

Python - 如何将字符串中的字符乘以字符后的数字

c# - .NET/C# - 将 char[] 转换为字符串

python - 数据框按大小分组到嵌套字典(多个层次结构)

python - 值错误 : Unknown label type: 'unknown'

python - 按顺序获取 NumPy 数据列的奇异值

java - java中的N维数组