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 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 giây, sử dụng phương thức TimeDeltaIndex.floor(). Với tần suất giây, truyền tham số freq bằng giá trị 'S'.

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

1. Import thư viện

import pandas as pd

2. Tạo 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. Thực hiện phép floor với tần suất giây

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

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...\n", tdIndex.components)
print("\nThực hiện phép Floor với tần suất giây...\n", tdIndex.floor(freq='S'))

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...
   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 giây...
TimedeltaIndex(['5 days 08:20:00', '0 days 17:42:19',
                '7 days 11:16:02', '0 days 22:35:25'],
               dtype='timedelta64[ns]', freq=None)

Giải thích: Phép floor với tần suất 'S' làm tròn xuống đến giây gần nhất, loại bỏ hoàn toàn phần mili-giây, micro-giây và nano-giây.