如何将Pandas查找表应用于NumPy数组?

8

I have a pandas Series like this:

      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]])
4个回答

6

通过使用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]])

2

使用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]
])

1
你可以使用 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]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接