简体   繁体   English

使用字典替换numpy数组元素

[英]Substitute numpy array elements using dictionary

I have this numpy array我有这个 numpy 数组

message = [ 97 98 114 97]

and this dictionary还有这本词典

codes = {97: '1', 98: '01', 114: '000'}

and I am now iterating through the numpy array and converting those numbers to the ones corresponding in the dictionary like this:我现在遍历 numpy 数组并将这些数字转换为字典中对应的数字,如下所示:

[codes[i] for i in message]

But this is really slow and takes a lot of memory, since I am creating a new list.但这真的很慢并且需要大量内存,因为我正在创建一个新列表。 Is there better approach?有更好的方法吗? Maybe one in which I will have still the same numpy array, but with the new numbers like this?也许我仍然拥有相同的 numpy 数组,但使用这样的新数字?

message = [1 01 000 1]

Here's a NumPythonic solution using np.searchsorted -这是使用np.searchsortedNumPythonic解决方案 -

np.asarray(codes.values())[np.searchsorted(codes.keys(),message)]

Please note that the output would be a NumPy array as well.请注意,输出也将是一个 NumPy 数组。 If you would like to have a list output, wrap it with .tolist() -如果你想要一个列表输出,用.tolist()包装它 -

np.asarray(codes.values())[np.searchsorted(codes.keys(),message)].tolist()

I would think the only bottleneck to this approach would be conversion to NumPy array with np.asarray() , as usually np.searchsorted is pretty efficient.我认为这种方法的唯一瓶颈是使用np.asarray()转换为 NumPy 数组,因为通常np.searchsorted非常有效。

Sample run -样品运行 -

In [36]: message = [ 97, 98, 114, 97]

In [37]: codes = {97: '1', 98: '01', 114: '000'}

In [38]: [codes[i] for i in message]
Out[38]: ['1', '01', '000', '1']

In [39]: np.asarray(codes.values())[np.searchsorted(codes.keys(),message)]
Out[39]: 
array(['1', '01', '000', '1'], 
      dtype='|S3')

you can very simply update in place:您可以非常简单地就地更新:

for i in np.arange(len(message)):
   message[i] = codes.get(message[i], message[i])

I'm sure there's a numpy specific syntax to iterate.我确定有一个 numpy 特定的语法可以迭代。 But note, you don't preserve the byte string since messages is of int type and your dict values appear to be byte arrays.但请注意,您不会保留字节字符串,因为messages是 int 类型并且您的 dict 值似乎是字节数组。 So you would need to copy to a new array to preserve type.因此,您需要复制到新数组以保留类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM