Gaol 是合并两个数据框,同时对公共(public)列中的行进行求和。
数据框 1:df1
df1 = pd.DataFrame({'year': ['2001', '2001', '2001', '2002', '2002'], 'month':['01','02','03', '01','02'], 'hits':[2, 3, 5, 12, 5], 'outs': [2, 0, 2, 1, 0] })
数据框 2:df2
df2 = pd.DataFrame({'year': ['2001', '2001', '2001', '2002', '2002', '2003', '2003'], 'month':['01','02','03', '01','02', '01','02'], 'hits':[2, 3, 5, 12, 5, 0, 0], 'outs': [2, 0, 2, 1, 0, 1, 4] })
保持列的顺序:
important = ['year', 'month']
reordered = important + [c for c in df1.columns if c not in important]
df1 = df1[reordered]
reordered = important + [c for c in df2.columns if c not in important]
df2 = df2[reordered]
df1
year month hits outs
0 2001 01 2 2
1 2001 02 3 0
2 2001 03 5 2
3 2002 01 12 1
4 2002 02 5 0
(Pdb) df2
year month hits outs
0 2001 01 2 2
1 2001 02 3 0
2 2001 03 5 2
3 2002 01 12 1
4 2002 02 5 0
5 2003 01 0 1
6 2003 02 0 4
我要实现的目标如下:
year month hits outs
0 2001 01 4 4
1 2001 02 6 0
2 2001 03 10 4
3 2002 01 24 2
4 2002 02 10 0
5 2003 01 0 1
6 2003 02 0 4
请注意,公共(public)列值已添加。
我尝试了以下操作:使用 concat
函数和 merge
函数
(Pdb) concat = pd.concat([df1, df2], axis=1)
(Pdb) concat
hits hits outs
year month
2001 01 2.0 2 2
02 3.0 3 0
03 5.0 5 2
2002 01 12.0 12 1
02 5.0 5 0
2003 01 NaN 0 1
02 NaN 0 4
(Pdb) concat.reset_index(inplace=True)
(Pdb) concat
year month hits hits outs
0 2001 01 2.0 2 2
1 2001 02 3.0 3 0
2 2001 03 5.0 5 2
3 2002 01 12.0 12 1
4 2002 02 5.0 5 0
5 2003 01 NaN 0 1
6 2003 02 NaN 0 4
(Pdb) combined = pd.merge(df1,df2, left_index=True, right_index=True)
(Pdb) combined.reset_index(inplace=True)
(Pdb) combined
year month hits_x hits_y outs
0 2001 01 2 2 2
1 2001 02 3 3 0
2 2001 03 5 5 2
3 2002 01 12 12 1
4 2002 02 5 5 0
我们如何在对行级别的公共(public)列求和时进行合并或连接。
最佳答案
合并 pd.concat
+ groupby
这是一种通用方法,可以容纳列表中任意数量的数据帧
pd.concat(
[df1, df2], ignore_index=True
).groupby(['year', 'month'], as_index=False).sum()
year month hits outs
0 2001 01 4 4
1 2001 02 6 0
2 2001 03 10 4
3 2002 01 24 2
4 2002 02 10 0
5 2003 01 0 1
6 2003 02 0 4
关于python - 合并或合并 pandas 数据框,同时汇总公共(public)列中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41642968/