Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Thực hiện phép toán floor trên TimeDeltaIndex với tần suất micro-giây

Để thực hiện phép toán floor (làm tròn xuống) trên TimeDeltaIndex với tần suất micro-giây, sử dụng phương thức TimeDeltaIndex.floor(). Với tần suất micro-giây, truyền tham số freq bằng giá trị 'us'.

Các bước thực hiện

1. Import thư viện cần thiết

import pandas as pd

2. Tạo đối tượng TimeDeltaIndex

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

3. Hiển thị TimeDeltaIndex

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

4. Thực hiện phép floor với tần suất micro-giây

print("\nThực hiện phép Floor với tần suất micro-giây...\n", tdIndex.floor(freq='us'))

Ví dụ hoàn chỉnh

import pandas as pd

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

print("TimeDeltaIndex...\n", tdIndex)
print("\nDataFrame các thành phần của TimeDeltas...\n", tdIndex.components)
print("\nThực hiện phép Floor với tần suất micro-giây...\n", tdIndex.floor(freq='us'))

Kết quả đầu ra

TimeDeltaIndex...
TimedeltaIndex(['5 days 08:20:00.000035045', '0 days 17:42:19.999999',
                '7 days 11:16:02.000055', '0 days 22:35:25.999999'],
               dtype='timedelta64[ns]', freq=None)

DataFrame các thành phần của TimeDeltas...
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     5      8       20        0             0            35           45
1     0     17       42       19           999           999            0
2     7     11       16        2             0            55            0
3     0     22       35       25           999           999            0

Thực hiện phép Floor với tần suất micro-giây...
TimedeltaIndex(['5 days 08:20:00.000035', '0 days 17:42:19.999999',
                '7 days 11:16:02.000055', '0 days 22:35:25.999999'],
               dtype='timedelta64[ns]', freq=None)

Lưu ý: Khác với tần suất mili-giây ('ms'), tần suất micro-giây ('us') giữ lại độ chính xác đến micro-giây và chỉ loại bỏ phần nano-giây.