【发布时间】:2021-08-09 12:55:54
【问题描述】:
我有
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 视为多列查找表
因此,如果数据帧中的键 B 和 C 恰好在系列索引中找到,我希望通过对 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 (None) and integer or boolean arrays are valid indices
还有:
df.apply(lambda x:lt[x.B,x.C],axis=1)
提高KeyError (357, 718)
我应该怎么做? 谢谢。
【问题讨论】:
-
您能否提供熊猫对象作为代码:
df.to_dict() -
{ 'B': {0: 356, 1: 357, 2: 358, 3: 359, 4: 360}, 'TF': {0: 'True', 1: 'True ', 2: '真', 3: '真', 4: '假'}, 'C': {0: 714, 1: 718, 2: 722, 3: 726, 4: 730}, 'N' : {0:1, 1:2, 2:3, 3:4, 4:5}}
标签: python pandas dataframe merge