Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - ดึงวันที่ในปี (ordinal day) จาก DateTimeIndex ด้วย dayofyear


คำอธิบาย

ใช้ property DateTimeIndex.dayofyear ดึงลำดับวันในปี (1-365/366) ของแต่ละ timestamp

ตัวอย่างโค้ด

import pandas as pd

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='D')

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nGet the ordinal day of year..\n", datetimeindex.dayofyear)

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+11:00', '2021-10-21 02:30:50+11:00',
               '2021-10-22 02:30:50+11:00', '2021-10-23 02:30:50+11:00',
               '2021-10-24 02:30:50+11:00', '2021-10-25 02:30:50+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='D')

Get the ordinal day of year..
Int64Index([293, 294, 295, 296, 297, 298], dtype='int64')

กรณีการใช้งาน

  • จัดกลุ่มข้อมูลตามวันในปี (seasonal analysis)
  • เปรียบเทียบข้อมูลปีละปีในวันเดียวกันของปี
  • คำนวณ day-of-year features สำหรับ ML