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

Python Pandas - วิธีดำเนินการ Ceil บน DateTimeIndex ด้วยความถี่ชั่วโมง

บทนำ

ใช้ DateTimeIndex.ceil() กับ freq='H' เพื่อปัดขึ้นเป็นหน่วยชั่วโมง

ขั้นตอน

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

import pandas as pd

2. สร้าง DateTimeIndex ความถี่ 20 นาที

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

3. ดำเนินการ Ceil ความถี่ชั่วโมง

print("\nPerforming ceil operation with hourly frequency...\n", datetimeindex.ceil(freq='H'))

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

import pandas as pd

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

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nPerforming ceil operation with hourly frequency...\n", datetimeindex.ceil(freq='H'))

ผลลัพธ์

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

DateTimeIndex frequency...
<20 * Minutes>

Performing ceil operation with hourly frequency...
DatetimeIndex(['2021-09-29 08:00:00+09:30', '2021-09-29 08:00:00+09:30',
               '2021-09-29 09:00:00+09:30', '2021-09-29 09:00:00+09:30',
               '2021-09-29 09:00:00+09:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq=None)

คำอธิบาย

เวลาถูกปัดขึ้นเป็นชั่วโมงเต็มถัดไป: 07:20 → 08:00, 07:40 → 08:00, 08:00:32 → 09:00, 08:20 → 09:00, 08:40 → 09:00 นาทีและวินาทีถูกรีเซ็ตเป็นศูนย์