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

Python Pandas - ส่งคืนตำแหน่งดัชนีของค่า ณ ช่วงเวลาหนึ่งของวันใน DateTimeIndex


ในการส่งคืนตำแหน่งดัชนีของค่า ณ ช่วงเวลาหนึ่งของวันใน DateTimeIndex ให้ใช้ DateTimeIndex.indexer_at_time() วิธีการ

ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import pandas as pd

สร้าง DatetimeIndex ด้วยจุด 5 และความถี่เป็น T เช่น นาที -

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

แสดง DateTimeIndex -

print("DateTimeIndex...\n", datetimeindex)

แสดงตำแหน่งดัชนีของค่าในช่วงเวลาเฉพาะของวัน เช่น 03:10:50 ที่นี่ –

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

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

import pandas as pd

# DatetimeIndex with period 5 and frequency as T i.e. minutes
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='20T')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# display index locations of values at particular time of day i.e. 03:10:50 here
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')
DateTimeIndex frequency...
<20 * Minutes>

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