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

Python Pandas - หาดัชนีที่เวลาตรงพอดีใน DateTimeIndex


คำอธิบาย

ใช้ DateTimeIndex.indexer_at_time() หาตำแหน่งดัชนีของค่าที่ส่วนเวลา (time component) ตรงกับเวลาที่ระบุพอดี

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

import pandas as pd

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='20T')

print("DateTimeIndex...\n", datetimeindex)
print("\nIndex locations of values at particular time of day...\n",
      datetimeindex.indexer_at_time('2021-10-30 03:10:50'))

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 02:50:50+10:30',
               '2021-10-30 03:10:50+10:30', '2021-10-30 03:30:50+10:30',
               '2021-10-30 03:50:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='20T')

Index locations of values at particular time of day...
[2]

หมายเหตุ

  • ค้นหาเฉพาะส่วนเวลา (เวลา 03:10:50) ไม่สนใจวันที่
  • คืนค่า array ของตำแหน่งดัชนี (integer positions)