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

Resample time series tìm tần suất cuối tháng (month-end) lớn nhất Python

Giả sử bạn có DataFrame time series tần suất tuần và muốn resample sang tần suất cuối tháng (Month End - 'M'), lấy giá trị lớn nhất (max) của mỗi tháng.

Giải pháp

  • Tạo DataFrame với cột thời gian date_range(freq='W').
  • Resample: df.resample('M', on='time_series').max().

Mã ví dụ

import pandas as pd

d = {'Id': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(d)
df['time_series'] = pd.date_range('01/01/2020', periods=10, freq='W')

print("DataFrame:\n", df)

print("\nMax month-end frequency:")
print(df.resample('M', on='time_series').max())

Kết quả

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

Max 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

Giải thích:

  • resample('M'): Gom nhóm theo cuối tháng (Month End).
  • on='time_series': Chỉ định cột datetime để resample (không phải index).
  • .max(): Lấy giá trị lớn nhất trong mỗi nhóm tháng.
  • Kết quả: Tháng 1 max Id=4 (ngày 26/1), Tháng 2 max Id=8 (23/2), Tháng 3 max Id=10 (8/3).