首页 > 解决方案 > 通过匹配来自另一个 Pandas 系列的多列索引来更新和求和 Pandas DataFrame

问题描述

我有

df =

     B     TF    C   N
0  356   True  714   1
1  357   True  718   2
2  358   True  722   3
3  359   True  726   4
4  360  False  730   5

lt=

 B    C  
356  714    223
360  730    101
400  800    200
Name: N, dtype: int64

type(lt) => pandas.core.series.Series

我喜欢将该系列lt 视为多列查找表

因此,如果在 Series 索引中准确找到键BCfrom 数据框,我喜欢通过对 的相应值求和来更新数据框N

所以我的最终数据框应该如下所示:

       B     TF    C  N
0    356   True  714  224
1    357   True  718  2
2    358   True  722  3
3    359   True  726  4
4    360  False  730  106

我该怎么办?我尝试了各种选项,例如:

df['N'] = df['N'] + df.apply(lambda x:lt[x[['B','C']]],axis=1)

但它给出了:

IndexError: only integers, slices (: ), ellipsis (...), numpy.newaxis () and integer or boolean arrays are valid indices

还:

df.apply(lambda x:lt[x.B,x.C],axis=1)

提高KeyError (357, 718)

我该怎么办?谢谢。

标签: pythonpandasdataframemerge

解决方案


使用mergeeval

out = df.merge(lt.reset_index(), on=['B', 'C'], how='left') \
        .fillna(0).eval('N = N_x + N_y') \
        .drop(columns=['N_x', 'N_y'])
>>> out
     B     TF    C      N
0  356   True  714  224.0
1  357   True  718    2.0
2  358   True  722    3.0
3  359   True  726    4.0
4  360  False  730  106.0

推荐阅读