什么是快速(非循环)的方法来应用一个dict到ndarray(意思是使用元素作为键和替换值) [英] What's a fast (non-loop) way to apply a dict to a ndarray (meaning use elements as keys and replace with values)

查看:185
本文介绍了什么是快速(非循环)的方法来应用一个dict到ndarray(意思是使用元素作为键和替换值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在循环,就像

new_data = [transform_dict[pt] for pt in line] for line in data]

但这太慢了。我已经尝试寻找一个合适的 numpy 方法,但是还没有找到任何东西。对于这种事情,是否有基于矩阵的实现?

But this is too slow. I've tried looking for a suitable numpy method but haven't found anything myself. Are there any matrix based implementations for this sort of thing?

推荐答案

在数组中转换您的字典,并使用 np.take

transform your dictionary in array and use np.take:

Na=1000 #array
Nd = 10**4 #dict
data=randint(0,Nd,(Na,Na))
dic=dict(zip(range(Nd),randint(0,Nd,Nd)))
dicarray=np.array(list(dic.values()))

通常要快得多: / p>

That is generally much faster :

In [3]: %timeit np.array([[dic[x] for x in line] for line in data]) 
1 loops, best of 3: 2.27 s per loop

In [4]: %timeit dicarray.take(data)
10 loops, best of 3: 24.4 ms per loop

这篇关于什么是快速(非循环)的方法来应用一个dict到ndarray(意思是使用元素作为键和替换值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆