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

Python Pandas: Chuyển PeriodIndex object thành Timestamp

Phương thức PeriodIndex.to_timestamp() trong Pandas chuyển đổi PeriodIndex thành DatetimeIndex (Timestamp). Nếu không chỉ định freq, mặc định sử dụng tần suất đầu kỳ (period start).

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

1. Import thư viện

import pandas as pd

2. Tạo PeriodIndex

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 (mặc định đầu kỳ)

print("\nPeriodIndex object to timestamp...\n", periodIndex.to_timestamp())

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())

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-01', '2019-01-01', '2020-01-01', '2022-01-01'], dtype='datetime64[ns]', freq=None)

Giải thích:

  • Không chỉ định freq → mặc định chuyển sang đầu kỳ (period start)
  • Tần suất Y (YearEnd) → đầu năm là 1/1
  • Kết quả: 2021-01-01, 2019-01-01, 2020-01-01, 2022-01-01

So sánh to_timestamp() với và không có freq

Gọi phương thức Kết quả cho period '2021' (YearEnd)
to_timestamp() 2021-01-01 (đầu năm)
to_timestamp(freq='M') 2021-01-31 (cuối tháng 1)
to_timestamp(freq='D') 2021-01-01 (đầu ngày)
to_timestamp(freq='A') 2021-12-31 (cuối năm)

Lưu ý: PeriodIndex lưu trữ ordinal values (số thứ tự) cho các kỳ thời gian đều đặn. Chuyển đổi sang timestamp phụ thuộc vào tần suất mục tiêu.