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

Python Pandas PeriodIndex: Chuyển PeriodArray sang tần suất chỉ định

Phương thức periodIndex.asfreq() trong Pandas chuyển đổi PeriodArray/PeriodIndex sang tần suất (frequency) được chỉ định. Điều này thay đổi độ chi tiết (granularity) của các period.

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo PeriodIndex tần suất năm

periodIndex = pd.PeriodIndex(
    ['2021-09-25 07:30:35', '2019-10-30 04:15:45', 
     '2020-07-15 02:55:15', '2022-06-25 09:40:55'], 
    freq="Y"
)

3. Hiển thị PeriodIndex

print("PeriodIndex...\n", periodIndex)

4. Chuyển sang tần suất tháng

print("\nConvert..\n", periodIndex.asfreq('M'))

Ví dụ hoàn chỉnh

import pandas as pd

periodIndex = pd.PeriodIndex(
    ['2021-09-25 07:30:35', '2019-10-30 04:15:45', 
     '2020-07-15 02:55:15', '2022-06-25 09:40:55'], 
    freq="Y"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
print("\nPeriodIndex frequency as string...\n", periodIndex.freqstr)
print("\nConvert..\n", periodIndex.asfreq('M'))

Kết quả đầu ra

PeriodIndex...
PeriodIndex(['2021', '2019', '2020', '2022'], dtype='period[A-DEC]')
PeriodIndex frequency object...
<YearEnd: month=12>
PeriodIndex frequency object as a string...
A-DEC
Convert..
PeriodIndex(['2021-12', '2019-12', '2020-12', '2022-12'], dtype='period[M]')

Giải thích:

  • Gốc: tần suất Y (YearEnd) → các năm 2021, 2019, 2020, 2022
  • Chuyển sang 'M' (MonthEnd) → mỗi năm trở thành tháng 12 của năm đó
  • Kết quả: 2021-12, 2019-12, 2020-12, 2022-12 (dtype period[M])

Quy tắc chuyển đổi tần suất

Từ (coarser) Sang (finer) Kết quả
Year (Y) Month (M) Tháng 12 của năm đó (YearEnd)
Year (Y) Day (D) 31/12 của năm đó
Quarter (Q) Month (M) Tháng cuối quý (3, 6, 9, 12)
Month (M) Day (D) Ngày cuối tháng (28/29/30/31)

Lưu ý: Chuyển từ tần suất thô (coarse) sang mịn (fine) lấy endpoint của kỳ gốc. Chuyển ngược (fine → coarse) dùng asfreq() với tần suất lớn hơn, sẽ nhóm các period.