【问题标题】:Pandas: sum all rows with the same month熊猫:对同一月份的所有行求和
【发布时间】:2019-12-09 03:05:06
【问题描述】:

假设我有以下数据:

| student      | performance | competititon | month   |
|--------------|-------------|--------------|---------|
| Aardvark     | 11          | A            | 2019-01 |
| Aardvark     | 13          | B            | 2019-01 |
| Jason Derulo | 11          | A            | 2019-01 |
| Jason Derulo | 15          | B            | 2019-01 |
| Jason Derulo | 22          | C            | 2019-02 |
| JP Saxe      | 11          | A            | 2019-01 |
| JP Saxe      | 23          | B            | 2019-01 |
| JP Saxe      | 32          | C            | 2019-02 |

我想要以下结果:

| student      | aggregate performance | month   |
|--------------|-----------------------|---------|
| Aardvark     | 24                    | 2019-01 |
| Jason Derulo | 26                    | 2019-01 |
| Jason Derulo | 22                    | 2019-02 |
| JP Saxe      | 34                    | 2019-01 |
| JP Saxe      | 32                    | 2019-02 |

简而言之,我希望将每个月的绩效列的总和,无论竞争如何,都放入一个新列表中。

我已经尝试过 wheregroupbysum 之类的东西,但我似乎无法完全得到我想要的东西。

【问题讨论】:

  • df.groupby(["student","month"])["aggregate performance"].agg(["sum"]).reset_index()

标签: python pandas dataframe row columnsorting


【解决方案1】:

让我们做

df.groupby(['month', 'student'])[['performance']].sum().reset_index()

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2014-12-15
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    相关资源
    最近更新 更多