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

Python Pandas - Làm tròn TimeDeltaIndex với tần suất micro-giây

Để làm tròn TimeDeltaIndex với tần suất micro-giây, sử dụng phương thức TimeDeltaIndex.round(). 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

import pandas as pd

2. Tạo TimeDeltaIndex

tdIndex = pd.TimedeltaIndex(data=[
    '10 day 5h 2 min 3us 10ns',
    '+22:39:19.999999',
    '2 day 4h 03:08:02.000045',
    '+07:20:32.261811624'
])

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

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

Ví dụ hoàn chỉnh

import pandas as pd

tdIndex = pd.TimedeltaIndex(data=[
    '10 day 5h 2 min 3us 10ns',
    '+22:39:19.999999',
    '2 day 4h 03:08:02.000045',
    '+07:20:32.261811624'
])

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

Kết quả đầu ra

TimeDeltaIndex...
TimedeltaIndex(['10 days 05:02:00.000003010', '0 days 22:39:19.999999',
                '2 days 07:08:02.000045', '0 days 07:20:32.261811624'],
               dtype='timedelta64[ns]', freq=None)

DataFrame các thành phần...
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0    10      5        2        0             0             3           10
1     0     22       39       19           999           999            0
2     2      7        8        2             0            45            0
3     0      7       20       32           261           811          624

Thực hiện phép Round với tần suất micro-giây...
TimedeltaIndex(['10 days 05:02:00.000003', '0 days 22:39:19.999999',
                '2 days 07:08:02.000045', '0 days 07:20:32.261812'],
               dtype='timedelta64[ns]', freq=None)

Giải thích: Với tần suất 'us', kết quả giữ độ chính xác đến micro-giây. Phần tử thứ 4: nano-giây 624 làm tròn micro-giây từ 811 lên 812. Các phần tử 1, 2, 3 đã có độ chính xác micro-giây nên giữ nguyên (phần tử 1 nano-giây 10 quá nhỏ để làm tròn lên).