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

Python Pandas: Chuyển PeriodIndex thành Timestamp và đặt tần suất

Phương thức PeriodIndex.to_timestamp() trong Pandas chuyển đổi PeriodIndex thành DatetimeIndex (Timestamp). Tham số freq cho phép đặt tần suất cho kết quả.

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

1. Import thư viện

import pandas as pd

2. Tạo PeriodIndex với tần suất năm (YearEnd)

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 Timestamp với tần suất tháng (MonthEnd)

print("\nPeriodIndex object to timestamp...\n", periodIndex.to_timestamp(freq='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("\nPeriodIndex object to timestamp...\n", periodIndex.to_timestamp(freq='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
PeriodIndex object to timestamp...
DatetimeIndex(['2021-01-31', '2019-01-31', '2020-01-31', '2022-01-31'], dtype='datetime64[ns]', freq=None)

Giải thích:

  • PeriodIndex gốc có tần suất Y (YearEnd, mặc định tháng 12)
  • Khi chuyển sang timestamp với freq='M' (MonthEnd), mỗi năm được chuyển thành cuối tháng 1 của năm đó
  • Kết quả là DatetimeIndex với các ngày 31/1 của từng năm

Các giá trị freq phổ biến cho to_timestamp()

freq Ý nghĩa Kết quả cho period '2021'
'D' Ngày 2021-01-01
'M' Cuối tháng 2021-01-31
'MS' Đầu tháng 2021-01-01
'Q' Cuối quý 2021-03-31
'A' Cuối năm 2021-12-31
'H' Giờ 2021-01-01 00:00