使用Numpy数组作为查找表 [英] Using Numpy arrays as lookup tables

查看:101
本文介绍了使用Numpy数组作为查找表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从.csv文件读取的Numpy数据的2D数组.每行代表一个数据点,最后一列包含一个键",该键与另一个Numpy数组中的键"唯一对应,即查找表".

I have a 2D array of Numpy data read from a .csv file. Each row represents a data point with the final column containing a a 'key' which corresponds uniquely to 'key' in another Numpy array - the 'lookup table' as it were.

将第一个表中的行与第二个表中的值进行匹配的最佳方式(最Numpythonic)是什么?

What is the best (most Numpythonic) way to match up the lines in the first table with the values in the second?

推荐答案

一些示例数据:

import numpy as np

lookup = np.array([[  1.     ,   3.14   ,   4.14   ],
                   [  2.     ,   2.71818,   3.7    ],
                   [  3.     ,  42.     ,  43.     ]])

a = np.array([[ 1, 11],
              [ 1, 12],
              [ 2, 21],
              [ 3, 31]])

在查找表中建立一个从键到行号的字典:

Build a dictionary from key to row number in the lookup table:

mapping = dict(zip(lookup[:,0], range(len(lookup))))

然后,您可以使用字典来匹配行.例如,如果您只想加入表:

Then you can use the dictionary to match up lines. For instance, if you just want to join the tables:

>>> np.hstack((a, np.array([lookup[mapping[key],1:] 
                            for key in a[:,0]])))
array([[  1.     ,  11.     ,   3.14   ,   4.14   ],
       [  1.     ,  12.     ,   3.14   ,   4.14   ],
       [  2.     ,  21.     ,   2.71818,   3.7    ],
       [  3.     ,  31.     ,  42.     ,  43.     ]])    

这篇关于使用Numpy数组作为查找表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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