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

Python Pandas - การทำ Ceil บน TimeDeltaIndex ด้วยความถี่มิลลิวินาที

หากต้องการทำการ Ceil (ปัดขึ้น) บน TimeDeltaIndex ด้วยความถี่มิลลิวินาที (Milliseconds) สามารถใช้เมธอด TimeDeltaIndex.ceil() พร้อมพารามิเตอร์ freq='ms'

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้างออบเจ็กต์ TimeDeltaIndex

tdIndex = pd.TimedeltaIndex(data=[
    '4 day 8h 20min 35us 45ns',
    '+17:42:19.999999',
    '9 day 3h 08:16:02.000055',
    '+22:35:25.000075'
])

3. แสดง TimeDeltaIndex

print("TimedeltaIndex...\n", tdIndex)

4. ทำ Ceil ด้วยความถี่มิลลิวินาที

print("\nทำ Ceil ด้วยความถี่มิลลิวินาที...\n", 
      tdIndex.ceil(freq='ms'))

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd

# สร้าง TimeDeltaIndex object
tdIndex = pd.TimedeltaIndex(data=[
    '4 day 8h 20min 35us 45ns',
    '+17:42:19.999999',
    '9 day 3h 08:16:02.000055',
    '+22:35:25.000075'
])

# แสดง TimedeltaIndex
print("TimedeltaIndex...\n", tdIndex)

# คืนค่า DataFrame ของส่วนประกอบ TimeDeltas
print("\nDataFrame ของส่วนประกอบ TimeDeltas...\n", tdIndex.components)

# Ceil operation บน TimeDeltaIndex ด้วยความถี่มิลลิวินาที
# สำหรับมิลลิวินาที ใช้ 'ms'
print("\nทำ Ceil ด้วยความถี่มิลลิวินาที...\n", 
      tdIndex.ceil(freq='ms'))

ผลลัพธ์ที่คาดหวัง

TimedeltaIndex... TimedeltaIndex(['4 days 08:20:00.000035045', '0 days 17:42:19.999999', '9 days 11:16:02.000055', '0 days 22:35:25.000075'], dtype='timedelta64[ns]', freq=None)
DataFrame ของส่วนประกอบ TimeDeltas...
    days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0      4      8       20        0             0            35           45
1      0     17       42       19           999           999            0
2      9     11       16        2             0            55            0
3      0     22       35       25             0            75            0
ทำ Ceil ด้วยความถี่มิลลิวินาที...
TimedeltaIndex(['4 days 08:20:00.001000', '0 days 17:42:20', '9 days 11:16:02.001000', '0 days 22:35:25.001000'], dtype='timedelta64[ns]', freq=None)

คำอธิบาย: การทำ Ceil ด้วยความถี่ 'ms' จะปัดค่าขึ้นเป็นมิลลิวินาทีที่ใกล้ที่สุด

  • 35.045 ไมโครวินาที → ปัดขึ้นเป็น 1 มิลลิวินาที (0.001 วินาที)
  • 999.999 มิลลิวินาที → ปัดขึ้นเป็น 1 วินาทีเต็ม
  • 55 ไมโครวินาที → ปัดขึ้นเป็น 1 มิลลิวินาที
  • 75 ไมโครวินาที → ปัดขึ้นเป็น 1 มิลลิวินาที