สมมติว่าคุณมี DataFrame ที่มีคอลัมน์ time series และต้องการ resample เป็นความถี่ท้ายเดือน (Month-end) แล้วหาค่าสูงสุดในแต่ละเดือน
วิธีแก้ปัญหา
- สร้าง DataFrame พร้อมคอลัมน์ time series (รายสัปดาห์)
- ใช้
df.resample('M', on='time_series').max()resample ท้ายเดือน หาค่าสูงสุด
ตัวอย่างโค้ด
import pandas as pd
d = {'Id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
df = pd.DataFrame(d)
# สร้าง time series 10 สัปดาห์
df['time_series'] = pd.date_range('01/01/2020', periods=10, freq='W')
print("DataFrame ต้นฉบับ:\n", df)
# Resample ท้ายเดือน (Month-end) หาค่าสูงสุด
print("\nค่าสูงสุดท้ายเดือน (Month-end frequency):")
print(df.resample('M', on='time_series').max())
ผลลัพธ์
DataFrame ต้นฉบับ:
Id time_series
0 1 2020-01-05
1 2 2020-01-12
2 3 2020-01-19
3 4 2020-01-26
4 5 2020-02-02
5 6 2020-02-09
6 7 2020-02-16
7 8 2020-02-23
8 9 2020-03-01
9 10 2020-03-08
ค่าสูงสุดท้ายเดือน (Month-end frequency):
Id time_series
time_series
2020-01-31 4 2020-01-26
2020-02-29 8 2020-02-23
2020-03-31 10 2020-03-08
คำอธิบาย:
resample('M', on='time_series'): จัดกลุ่มข้อมูลตามความถี่ท้ายเดือน (Month-end) โดยใช้คอลัมน์ time_series เป็นฐาน.max(): หาค่าสูงสุดในแต่ละกลุ่ม (ต่อคอลัมน์ตัวเลข)- ความถี่อื่นๆ: 'D'=วัน, 'W'=สัปดาห์, 'M'=ท้ายเดือน, 'MS'=ต้นเดือน, 'Q'=ไตรมาส, 'A'=ปี
- ผลลัพธ์ index จะเป็นวันที่ท้ายเดือนของแต่ละกลุ่ม