Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python – Groupby theo tháng và tính tổng cột trong Pandas DataFrame

Giới thiệu

Để nhóm DataFrame theo tháng (dựa trên cột datetime) và tính tổng của cột số, dùng pd.Grouper với freq='M' trong groupby.

Ví dụ minh họa

import pandas as pd

# DataFrame với cột datetime
dataFrame = pd.DataFrame(
    {
        "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"],
        "Date_of_Purchase": [
            pd.Timestamp("2021-06-10"),
            pd.Timestamp("2021-07-11"),
            pd.Timestamp("2021-06-25"),
            pd.Timestamp("2021-06-29"),
            pd.Timestamp("2021-03-20"),
            pd.Timestamp("2021-01-22"),
            pd.Timestamp("2021-01-06"),
            pd.Timestamp("2021-01-04"),
            pd.Timestamp("2021-05-09")
        ],
        "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
    }
)
print("DataFrame...\n", dataFrame)

# Group by month (freq='M') trên cột Date_of_Purchase, tính sum
print("\nGroup by tháng, tổng Reg_Price:")
print(dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='M')).sum())

Kết quả đầu ra

DataFrame...
       Car Date_of_Purchase  Reg_Price
0     Audi       2021-06-10       1000
1   Lexus       2021-07-11       1400
2   Tesla       2021-06-25       1100
3 Mercedes       2021-06-29        900
4    BMW       2021-03-20       1700
5  Toyota       2021-01-22       1800
6  Nissan       2021-01-06       1300
7 Bentley       2021-01-04       1150
8 Mustang       2021-05-09       1350

Group by tháng, tổng Reg_Price:
            Reg_Price
Date_of_Purchase
2021-01-31     4250.0
2021-02-28        NaN
2021-03-31     1700.0
2021-04-30        NaN
2021-05-31     1350.0
2021-06-30     3000.0
2021-07-31     1400.0

Giải thích: pd.Grouper(key='Date_of_Purchase', freq='M') nhóm theo cuối tháng. Tháng không có dữ liệu hiện NaN (có thể fillna(0)).