gpt4 book ai didi

python - 快速替换 numpy 数组中的值

转载 作者:IT老高 更新时间:2023-10-28 21:37:25 26 4
gpt4 key购买 nike

我有一个非常大的 numpy 数组(最多包含一百万个元素),如下所示:

[0,1,6,5,1,2,7,6,2,3,8,7,3,4,9,8,5,6,11,10,6,7,12,11,7,
8,13,12,8,9,14,13,10,11,16,15,11,12,17,16,12,13,18,17,13,
14,19,18,15,16,21,20,16,17,22,21,17,18,23,22,18,19,24,23]

以及用于替换上述数组中某些元素的小字典映射

{4: 0, 9: 5, 14: 10, 19: 15, 20: 0, 21: 1, 22: 2, 23: 3, 24: 0}

我想根据上面的 map 替换一些元素。 numpy 数组真的很大,只有一小部分元素(作为字典中的键出现)会被相应的值替换。最快的方法是什么?

最佳答案

我相信还有更有效的方法,但现在,尝试一下

from numpy import copy

newArray = copy(theArray)
for k, v in d.iteritems(): newArray[theArray==k] = v

微基准测试和正确性测试:

#!/usr/bin/env python2.7

from numpy import copy, random, arange

random.seed(0)
data = random.randint(30, size=10**5)

d = {4: 0, 9: 5, 14: 10, 19: 15, 20: 0, 21: 1, 22: 2, 23: 3, 24: 0}
dk = d.keys()
dv = d.values()

def f1(a, d):
b = copy(a)
for k, v in d.iteritems():
b[a==k] = v
return b

def f2(a, d):
for i in xrange(len(a)):
a[i] = d.get(a[i], a[i])
return a

def f3(a, dk, dv):
mp = arange(0, max(a)+1)
mp[dk] = dv
return mp[a]


a = copy(data)
res = f2(a, d)

assert (f1(data, d) == res).all()
assert (f3(data, dk, dv) == res).all()

结果:

$ python2.7 -m timeit -s 'from w import f1,f3,data,d,dk,dv' 'f1(data,d)'
100 loops, best of 3: 6.15 msec per loop

$ python2.7 -m timeit -s 'from w import f1,f3,data,d,dk,dv' 'f3(data,dk,dv)'
100 loops, best of 3: 19.6 msec per loop

关于python - 快速替换 numpy 数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3403973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com