หากต้องการคำนวณ TimedeltaArray ของความต่างระหว่างค่า DateTimeIndex กับการแปลงเป็น PeriodArray ที่ความถี่ที่กำหนด สามารถใช้เมธอด datetimeindex.to_perioddelta() พร้อมพารามิเตอร์ freq
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้าง DatetimeIndex
datetimeindex = pd.date_range(
'2021-10-18 07:20:32.261811624',
periods=5,
freq='2Y'
)
3. แสดง DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
4. คำนวณ PeriodDelta (ความต่างกับ Period)
กำหนดความถี่ Period ด้วย freq='M' (รายเดือน)
print("\nDateTimeIndex to PeriodDelta...\n",
datetimeindex.to_perioddelta(freq='M'))
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# DatetimeIndex with period 5 and frequency as Y i.e. year
datetimeindex = pd.date_range(
'2021-10-18 07:20:32.261811624',
periods=5,
freq='2Y'
)
# แสดง DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# แสดง DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# แปลง DateTimeIndex เป็น Period (ความถี่เดือน)
print("\nDateTimeIndex to Period (freq='M')...\n",
datetimeindex.to_period(freq='M'))
# คำนวณ TimedeltaArray ความต่างระหว่าง index values และ PeriodArray
print("\nDateTimeIndex to PeriodDelta (freq='M')...\n",
datetimeindex.to_perioddelta(freq='M'))
ผลลัพธ์ที่คาดหวัง
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 frequency... <2 * YearEnds: month=12>
DateTimeIndex to Period (freq='M')...
PeriodIndex(['2021-12', '2023-12', '2025-12', '2027-12', '2029-12'], dtype='period[M]')
DateTimeIndex to PeriodDelta (freq='M')...
TimedeltaIndex(['30 days 07:20:32.261811624', '30 days 07:20:32.261811624', '30 days 07:20:32.261811624', '30 days 07:20:32.261811624', '30 days 07:20:32.261811624'], dtype='timedelta64[ns]', freq=None)
คำอธิบาย:
to_period(freq='M'): แปลงแต่ละ timestamp เป็น Period เดือน (2021-12, 2023-12, ...)to_perioddelta(freq='M'): คำนวณความต่างระหว่าง timestamp ต้นฉบับกับจุดเริ่มต้นของ Period นั้น (คือ 1 ธันวาคม 00:00:00)- ผลลัพธ์ทั้งหมดเป็น
30 days 07:20:32.261811624เพราะ 31 ธันวาคม - 1 ธันวาคม = 30 วัน + เวลา 07:20:32... - ใช้ได้กับการวิเคราะห์ offset ภายใน Period (เช่น "วันที่กี่ของเดือน", "เวลาเท่าไหร่ในช่วง Period")
การใช้งาน freq อื่นๆ
# ความต่างกับจุดเริ่มต้นของวัน
print(datetimeindex.to_perioddelta(freq='D'))
# ความต่างกับจุดเริ่มต้นของชั่วโมง
print(datetimeindex.to_perioddelta(freq='H'))