【问题标题】:Combining DataFrame on Datetime index, summing values in other rows if same index在 Datetime 索引上组合 DataFrame,如果索引相同,则将其他行中的值相加
【发布时间】:2023-04-06 23:02:01
【问题描述】:

我有两个具有相同列的 DataFrame,我希望将它们组合起来,因此最终的 DataFrame 只有一组唯一的日期,但 Count 列会针对数据框中的任何匹配日期求和。这是一个例子:

数据帧1

     Date        Count
0    2020-01-01    5
1    2020-01-02    10

数据帧2

     Date        Count
0    2020-01-01    10
1    2020-01-03    20

结果

     Date        Count
0    2020-01-01    15
1    2020-01-02    10
3    2020-01-03    20

最好的方法是什么?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    尝试使用groupbypd.concat

    res = (pd.concat([df1,df2],axis=0)).groupby('Date')['Count'].sum().reset_index()
    

    会得到你:

             Date  Count
    0  2020-01-01     15
    1  2020-01-02     10
    2  2020-01-03     20
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 2021-07-02
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多