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

Python Pandas - วิธีปัดเศษ DateTimeIndex ด้วยความถี่วินาที

บทนำ

ใช้ DateTimeIndex.round() พร้อม freq='S' เพื่อปัดเศษเป็นหน่วยวินาที

ขั้นตอน

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

import pandas as pd

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

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

3. แสดงข้อมูลและดำเนินการ Round

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

res = datetimeindex.second
print("\nThe second from DateTimeIndex...\n", res)

print("\nPerforming round operation with seconds frequency...\n", datetimeindex.round(freq='S'))

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

import pandas as pd

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

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
res = datetimeindex.second
print("\nThe second from DateTimeIndex...\n", res)
print("\nPerforming round operation with seconds frequency...\n", datetimeindex.round(freq='S'))

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30', '2021-09-29 07:21:00.261811624+09:30',
               '2021-09-29 07:21:28.261811624+09:30', '2021-09-29 07:21:56.261811624+09:30',
               '2021-09-29 07:22:24.261811624+09:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq='28S')

DateTimeIndex frequency...
<28 * Seconds>

The second from DateTimeIndex...
Int64Index([32, 0, 28, 56, 24], dtype='int64')

Performing round operation with seconds frequency...
DatetimeIndex(['2021-09-29 07:20:32+09:30', '2021-09-29 07:21:00+09:30',
               '2021-09-29 07:21:28+09:30', '2021-09-29 07:21:56+09:30',
               '2021-09-29 07:22:24+09:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq=None)

คำอธิบาย

ส่วนทศนิยมของวินาทีถูกปัดเศษ: 32.261811624 → 32 (เพราะ .261 < .5) ไมโครวินาทีถูกลบออก วินาทีที่เป็นจำนวนเต็มแล้วคงเดิม