Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - จัดกลุ่ม Pandas DataFrame ตามปี (Group by Year)

บทนำ

ใช้ groupby() ร่วมกับ pd.Grouper จัดกลุ่มข้อมูลตามปี คำนวณผลรวม Reg_Price ทุก 3 ปี

ขั้นตอน

  1. สร้าง DataFrame มีคอลัมน์ Date_of_Purchase (Timestamp) และ Reg_Price
  2. จัดกลุ่มด้วย pd.Grouper(key='Date_of_Purchase', freq='3Y') แล้ว .sum()

โค้ดเต็ม

import pandas as pd

dataFrame = pd.DataFrame({
    "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"],
    "Date_of_Purchase": [pd.Timestamp("2021-06-10"), pd.Timestamp("2019-07-11"),
        pd.Timestamp("2016-06-25"), pd.Timestamp("2021-06-29"), pd.Timestamp("2020-03-20"),
        pd.Timestamp("2019-01-22"), pd.Timestamp("2011-01-06"), pd.Timestamp("2013-01-04"),
        pd.Timestamp("2014-05-09")],
    "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
})
print("DataFrame...\n", dataFrame)

result = dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='3Y')).sum()
print("\nGroup Dataframe by 3 years...\n", result)

ผลลัพธ์

ได้ผลรวม Reg_Price จัดกลุ่มทุก 3 ปี: 2011, 2014, 2017, 2020, 2023