【问题标题】:Python Pandas group by month and yearPython Pandas 按月和年分组
【发布时间】:2019-10-30 07:34:22
【问题描述】:

我有以下,

import pandas as pd

data = [['AAA','2019-01-01', 10], ['AAA','2019-01-02', 20],
        ['AAA','2019-02-01', 30], ['AAA','2019-02-02', 40],
        ['BBB','2019-01-01', 50], ['BBB','2019-01-02', 60],
        ['BBB','2019-02-01', 70],['BBB','2019-02-02', 80]]

dfx = pd.DataFrame(data, columns = ['NAME', 'TIMESTAMP','VALUE'])

  NAME   TIMESTAMP  VALUE
0  AAA  2019-01-01     10
1  AAA  2019-01-02     20
2  AAA  2019-02-01     30
3  AAA  2019-02-02     40
4  BBB  2019-01-01     50
5  BBB  2019-01-02     60
6  BBB  2019-02-01     70
7  BBB  2019-02-02     80

我正在尝试对“TIMESTAMP”和“NAME”列中按 MONTH 和 YEAR 分组的“VALUE”列求和。

所以最终期望的输出是,

  NAME   TIMESTAMP  VALUE SUM
0  AAA  2019-01-01     10  30
1  AAA  2019-01-02     20  30
2  AAA  2019-02-01     30  70
3  AAA  2019-02-02     40  70
4  BBB  2019-01-01     50 110
5  BBB  2019-01-02     60 110
6  BBB  2019-02-01     70 150
7  BBB  2019-02-02     80 150

我如何得到这个输出?

谢谢。

【问题讨论】:

    标签: python-3.x pandas pandas-groupby


    【解决方案1】:

    使用 GroupBy.transform 和 Series.dt.year 和 Series.dt.month:

    d = pd.to_datetime(dfx['TIMESTAMP'])
    dfx['SUM'] = (dfx.groupby(['NAME', 
                               dfx['TIMESTAMP'].dt.year, 
                               dfx['TIMESTAMP'].dt.month])['VALUE']
                     .transform('sum'))
    

    或Series.dt.to_period的月份:

    dfx['SUM'] = (dfx.groupby(['NAME', dfx['TIMESTAMP'].dt.to_period('m')])['VALUE']
                     .transform('sum'))
    

    print (dfx)
      NAME   TIMESTAMP  VALUE  SUM
    0  AAA  2019-01-01     10   30
    1  AAA  2019-01-02     20   30
    2  AAA  2019-02-01     30   70
    3  AAA  2019-02-02     40   70
    4  BBB  2019-01-01     50  110
    5  BBB  2019-01-02     60  110
    6  BBB  2019-02-01     70  150
    7  BBB  2019-02-02     80  150
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2019-04-17
      相关资源
      最近更新 更多