python - 通过匹配来自另一个 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 索引中准确找到键B
和C
from 数据框,我喜欢通过对 的相应值求和来更新数据框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)
我该怎么办?谢谢。
解决方案
使用merge
和eval
:
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
推荐阅读
- php - 传递控制器以查看未定义变量时出现未定义变量错误:用户(查看:C:\xampp\htdocs\site\resources\views\edit.blade.php)
- python - 如何在传入格式未知的字符串中随机化数字?
- java - Java UserDefinedFileAttributeView 空
- javascript - 如何使用 onclick 隐藏同一类的所有 div?
- mongodb - 每个文档的 MongoDB 字段/键限制
- c# - aspnet core 3.1 中的 Linq groupby 无法处理 LINQ 表达式
- tensorflow - tensorflow2.0中是否有pytorch的最大操作?
- python - 如何返回 DataFrame 并为 numpy.average 添加列?
- c++ - 如何使用动态编程来切割长度为 n 的杆,使其最有利可图
- javascript - 将 Hooks 函数导出为 react 组件的正确方法是什么?