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

Python Pandas - วิธีดำเนินการ Floor บน DateTimeIndex ด้วยความถี่นาที

บทนำ

ใช้ DateTimeIndex.floor() กับ freq='T' เพื่อปัดลงเป็นหน่วยนาที

ขั้นตอน

1. นำเข้าไลบรารี

import pandas as pd

2. สร้าง DateTimeIndex

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='40S')

3. ดำเนินการ Floor ความถี่นาที

print("\nPerforming floor operation with minute frequency...\n", datetimeindex.floor(freq='T'))

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

import pandas as pd

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='40S')

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

# getting the minute
res = datetimeindex.minute
print("\nThe minute from DateTimeIndex...\n", res)

print("\nPerforming floor operation with minute frequency...\n", datetimeindex.floor(freq='T'))

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30', '2021-10-18 07:21:12.261811624+10:30',
               '2021-10-18 07:21:52.261811624+10:30', '2021-10-18 07:22:32.261811624+10:30',
               '2021-10-18 07:23:12.261811624+10:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq='40S')

DateTimeIndex frequency...
<40 * Seconds>

The minute from DateTimeIndex...
Int64Index([20, 21, 21, 22, 23], dtype='int64')

Performing floor operation with minute frequency...
DatetimeIndex(['2021-10-18 07:20:00+10:30', '2021-10-18 07:21:00+10:30',
               '2021-10-18 07:21:00+10:30', '2021-10-18 07:22:00+10:30',
               '2021-10-18 07:23:00+10:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq=None)

คำอธิบาย

เวลาถูกปัดลงเป็นนาทีปัจจุบัน: 07:20:32 → 07:20:00, 07:21:12 → 07:21:00, 07:21:52 → 07:21:00 วินาทีถูกรีเซ็ตเป็นศูนย์