Python 将两个数据帧添加到一起时出现关键错误
帧Python 将两个数据帧添加到一起时出现关键错误,python,pandas,Python,Pandas,帧df1和df2,我想把它们加在一起,形成df3。部分数据帧(因为它们非常大)如下所示 df1: total_pnl_per_pos invested date 2015-03-17 0.330533 145790.529585 2015-03-18 -0.132040 152116.458134 2015-03-19 0.189508 141
df1
和df2
,我想把它们加在一起,形成df3
。部分数据帧(因为它们非常大)如下所示
df1
:
total_pnl_per_pos invested
date
2015-03-17 0.330533 145790.529585
2015-03-18 -0.132040 152116.458134
2015-03-19 0.189508 141114.361229
2015-03-20 0.346906 323712.355051
2015-03-21 -0.004500 149999.909424
df2
:
total_pnl_per_pos invested
date
2015-03-16 -0.009346 3843277.00
2015-03-17 -0.025422 4495925.00
2015-03-18 -0.093223 4233412.00
2015-03-19 -0.144945 4340475.00
2015-03-20 -0.030945 6107379.00
我希望df3
成为df1
+df1
并且看起来像:
total_pnl_per_pos invested
date
2015-03-16 -0.009346 3843277
2015-03-17 0.305111 4641715.53
2015-03-18 -0.225263 4385528.458
2015-03-19 0.044563 4481589.361
2015-03-20 0.315961 6431091.355
2015-03-21 -0.0045 149999.9094
请注意,df1和df2是按日期索引的,在每个数据帧中不一定有相同的日期
我尝试使用:
df3= df1.set_index('date').add(df2.set_index('date'), fill_value=0).reset_index()
及
然而,当我尝试这两种不同的解决方案时,我得到了一个
KeyError:'date'
错误。我哪里出错了?看起来日期已经是索引了。换句话说,您不能两次将日期指定为索引。因此,下文将起作用:
df3 = df1.add(df2, axis='index', fill_value=0)
输出:
total_pnl_per_pos invested
date
2015-03-16 -0.009346 3.843277e+06
2015-03-17 0.305111 4.641716e+06
2015-03-18 -0.225263 4.385528e+06
2015-03-19 0.044563 4.481589e+06
2015-03-20 0.315961 6.431091e+06
2015-03-21 -0.004500 1.499999e+05
希望这能有所帮助。date
此处用作索引,不能作为列访问。尝试df3=pd.concat([df1,df2]).reset_index().groupby('date').sum().reset_index()
total_pnl_per_pos invested
date
2015-03-16 -0.009346 3.843277e+06
2015-03-17 0.305111 4.641716e+06
2015-03-18 -0.225263 4.385528e+06
2015-03-19 0.044563 4.481589e+06
2015-03-20 0.315961 6.431091e+06
2015-03-21 -0.004500 1.499999e+05