【问题标题】:How to apply a Pandas lookup table to a numpy array?如何将 Pandas 查找表应用于 numpy 数组?
【发布时间】:2018-07-11 06:46:02
【问题描述】:

我有一个这样的熊猫系列:

      measure
0    0.3
6    0.6
9    0.2
11   0.3
14   0.0
17   0.1
23   0.9

还有一个像这样的 numpy 数组:

array([[ 0,  0,  9, 11],
       [ 6, 14,  6, 17]])

如何从 numpy 数组中的值到系列中的索引进行查找以获得此:

array([[ 0.3,  0.3,  0.2, 0.3],
       [ 0.6,  0.0,  0.6, 0.1]])

【问题讨论】:

    标签: python python-3.x pandas numpy dictionary


    【解决方案1】:

    通过np.vectorize,带有系列s和数组a

    np.vectorize(s.get)(a)
    

    【讨论】:

      【解决方案2】:

      使用replace

      a=np.array([[ 0,  0,  9, 11],
             [ 6, 14,  6, 17]])
      pd.DataFrame(a).replace(df.measure.to_dict()).values
      Out[214]: 
      array([[0.3, 0.3, 0.2, 0.3],
             [0.6, 0. , 0.6, 0.1]])
      

      【讨论】:

        【解决方案3】:

        使用np.bincount的有趣方式

        np.bincount(s.index.values, s.values)[a]
        
        array([[ 0.3,  0.3,  0.2,  0.3],
               [ 0.6,  0. ,  0.6,  0.1]])
        

        设置

        s = pd.Series(
            [.3, .6, .2, .3, .0, .1, .9],
            [0, 6, 9, 11, 14, 17, 23]
        )
        
        a = np.array([
            [0, 0, 9, 11],
            [6, 14, 6, 17]
        ])
        

        【讨论】:

          【解决方案4】:

          你可以使用 loc 和 reshape:

          s = pd.Series({0: 0.3, 6: 0.6, 9: 0.2, 11: 0.3, 14: 0.0, 17: 0.1, 23: 0.9})
          
          a = np.array([[ 0,  0,  9, 11],
                       [ 6, 14,  6, 17]])
          
          s.loc[a.flatten()].values.reshape(a.shape)
          Out[192]: 
          array([[ 0.3,  0.3,  0.2,  0.3],
                 [ 0.6,  0. ,  0.6,  0.1]])
          

          或者:

          pd.DataFrame(a).applymap(lambda x: s.loc[x]).values
          Out[200]: 
          array([[ 0.3,  0.3,  0.2,  0.3],
                 [ 0.6,  0. ,  0.6,  0.1]])
          

          【讨论】:

            猜你喜欢
            • 2018-02-04
            • 2015-11-12
            • 2020-05-25
            • 1970-01-01
            • 1970-01-01
            • 2017-12-23
            • 2019-07-25
            • 1970-01-01
            • 2018-09-05
            相关资源
            最近更新 更多