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

Python Pandas - ปัดเศษ DateTimeIndex ด้วยความถี่เป็นจำนวนเท่าของหน่วยเดียว

บทนำ

ใช้ DateTimeIndex.round() กับ freq='10T' (10 นาที) เพื่อปัดเศษเป็นจำนวนเท่าของหน่วยเดียว

ขั้นตอน

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

import pandas as pd

2. สร้าง DateTimeIndex ความถี่ 1 ชั่วโมง

datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='H')

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

print("\nPerforming round operation with multiples of a single unit frequency...\n", datetimeindex.round(freq='10T'))

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

import pandas as pd

datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='H')

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nPerforming round operation with multiples of a single unit frequency...\n", datetimeindex.round(freq='10T'))

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30', '2021-09-29 08:20:32.261811624+09:30',
               '2021-09-29 09:20:32.261811624+09:30', '2021-09-29 10:20:32.261811624+09:30',
               '2021-09-29 11:20:32.261811624+09:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq='H')

DateTimeIndex frequency...
<Hour>

Performing round operation with multiples of a single unit frequency...
DatetimeIndex(['2021-09-29 07:20:00+09:30', '2021-09-29 08:20:00+09:30',
               '2021-09-29 09:20:00+09:30', '2021-09-29 10:20:00+09:30',
               '2021-09-29 11:20:00+09:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq=None)

คำอธิบาย

เวลาถูกปัดเศษเป็นช่วง 10 นาทีที่ใกล้ที่สุด: 07:20:32 → 07:20:00 (เพราะ 32 วินาที < 5 นาที) นาทีที่ไม่ใช่ตัวคูณของ 10 จะถูกปัดตามหลักการปัดเศษมาตรฐาน