Using Numpy arrays as lookup tables

后端 未结 2 1922
无人及你
无人及你 2021-01-12 01:20

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

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 01:55

    Some example data:

    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.     ]])    
    

提交回复
热议问题