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

Python Pandas - Chuyển DateTimeIndex sang Period

Để chuyển DateTimeIndex sang PeriodIndex (chu kỳ thời gian), sử dụng phương thức DateTimeIndex.to_period(freq).

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

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex

datetimeindex = pd.date_range(
    '2021-10-18 07:20:32.261811624',
    periods=5,
    freq='2Y'
)

3. Chuyển sang Period với tần suất tháng ('M')

print("\nDateTimeIndex to Period (freq='M')...\n",
      datetimeindex.to_period(freq='M'))

Ví dụ hoàn chỉnh

import pandas as pd

datetimeindex = pd.date_range(
    '2021-10-18 07:20:32.261811624',
    periods=5,
    freq='2Y'
)

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nDateTimeIndex to Period (freq='M')...\n",
      datetimeindex.to_period(freq='M'))

Kết quả đầu ra

DateTimeIndex...
DatetimeIndex(['2021-12-31 07:20:32.261811624', '2023-12-31 07:20:32.261811624',
               '2025-12-31 07:20:32.261811624', '2027-12-31 07:20:32.261811624',
               '2029-12-31 07:20:32.261811624'],
              dtype='datetime64[ns]', freq='2A-DEC')

DateTimeIndex to Period (freq='M')...
PeriodIndex(['2021-12', '2023-12', '2025-12', '2027-12', '2029-12'], dtype='period[M]')

Các tần suất (freq) thường dùng

Period vs Timestamp

  • Timestamp: Thời điểm cụ thể (có nanosecond)
  • Period: Khoảng thời gian (span) - ví dụ cả tháng 12/2021
  • Period hỗ trợ phép toán: period + 1 (tháng sau), period.asfreq('D') (chuyển sang ngày)
MãÝ nghĩaVí dụ
DNgày2021-12-31
WTuần2021-12-27/2022-01-02
MTháng2021-12
QQuý2021Q4
A / YNăm2021
HGiờ2021-12-31 07
T / minPhút2021-12-31 07:20
SGiây2021-12-31 07:20:32