เพื่อแปลง PeriodIndex object เป็น Timestamp ให้ใช้เมธอด PeriodIndex.to_timestamp()
ขั้นตอนตัวอย่าง
import pandas as pd
# สร้าง PeriodIndex object (freq="Y" = รายปี)
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("\nความถี่ PeriodIndex...\n", periodIndex.freq)
print("\nความถี่ PeriodIndex เป็นสตริง...\n", periodIndex.freqstr)
# แปลงเป็น Timestamp (ไม่ระบุ freq ใช้ค่าเริ่มต้น)
print("\nPeriodIndex แปลงเป็น Timestamp...\n", periodIndex.to_timestamp())
โค้ดเต็มและผลลัพธ์
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("\nความถี่ PeriodIndex...\n", periodIndex.freq)
print("\nความถี่ PeriodIndex เป็นสตริง...\n", periodIndex.freqstr)
print("\nPeriodIndex แปลงเป็น Timestamp...\n", periodIndex.to_timestamp())
PeriodIndex...
PeriodIndex(['2021', '2019', '2020', '2022'], dtype='period[A-DEC]')
ความถี่ PeriodIndex...
ความถี่ PeriodIndex เป็นสตริง...
A-DEC
PeriodIndex แปลงเป็น Timestamp...
DatetimeIndex(['2021-01-01', '2019-01-01', '2020-01-01', '2022-01-01'], dtype='datetime64[ns]', freq=None)
หมายเหตุ: โดยไม่ระบุ freq จะคืนค่าเริ่มต้นของช่วงเวลา (วันแรกของปี)