【问题标题】:Summarize rows with same values on specific columns in Pandas汇总 Pandas 中特定列上具有相同值的行
【发布时间】:2020-03-24 15:31:41
【问题描述】:

对于一个大学项目,我使用约翰霍普金斯大学冠状病毒 COVID-19 数据集:https://github.com/CSSEGISandData/COVID-19。我正在尝试使数据集更简单。这是我现在的数据集:

        Country         Date        Confirmed   Deaths  Recovered
2600    Mainland China  2020-02-28  410.0       7.0     257.0
2601    Iran            2020-02-28  388.0       34.0    73.0
2602    Mainland China  2020-02-28  337.0       3.0     279.0
2603    Mainland China  2020-02-28  318.0       6.0     277.0
2604    Mainland China  2020-02-28  296.0       1.0     235.0
...     ...             ...         ...         ...     ...
2695    US              2020-02-25  1.0         0.0     1.0
2696    US              2020-02-24  0.0         0.0     0.0
2697    US              2020-02-24  0.0         0.0     0.0
2698    US              2020-02-24  0.0         0.0     0.0
2699    Mainland China  2020-02-29  66337.0     2727.0  28993.0

如果 Country 和 Date 列中的值相同,我想汇总所有 Confirmed、Deaths 和 Recovered 值。

例如,在第 2600、2602、2603、2604 行中,Country 和 Date 列中的值匹配,因此我想合并这些行并分别汇总 Confirmed、Deaths 和 Recovered 列。这应该给出以下行:

 2600    Mainland China  2020-02-28  1361.0       17.0     1048.0

到目前为止我所拥有的:

duplicateRowsDF = df[df.duplicated(['Country', 'Date'])]
duplicateRowsDF

希望有人可以帮助我,最好是但不限于 Pandas。提前致谢。

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    使用groupby 怎么样?如果你这样做:

    df.groupby(by=['Country', 'Date']).sum() 
    

    所有具有相同国家和日期的行将被分组到一列中,每列中所有值的总和。

    【讨论】:

    • 是的,很好用。我将其更改为: df= df.groupby(by=['Date', 'Country']).sum() 以便所有内容都按日期分组。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2022-11-20
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多