Để làm tròn TimeDeltaIndex với tần suất giây, sử dụng phương thức TimeDeltaIndex.round(). 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 (dữ liệu hơi khác bài trước)
tdIndex = pd.TimedeltaIndex(data=[
'10 day 5h 2 min 3us 10ns',
'+22:39:19.999999',
'2 day 4h 03:08:02.000045',
'+21:15:45.999999' # Thay đổi từ bài trước
])
4. Thực hiện phép round với tần suất giây
print("\nThực hiện phép Round với tần suất giây...\n", tdIndex.round(freq='S'))
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',
'+21:15:45.999999'
])
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 giây...\n", tdIndex.round(freq='S'))
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 21:15:45.999999'],
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 21 15 45 999 999 0
Thực hiện phép Round với tần suất giây...
TimedeltaIndex(['10 days 05:02:00', '0 days 22:39:20',
'2 days 07:08:02', '0 days 21:15:46'],
dtype='timedelta64[ns]', freq=None)
Giải thích: Phép round với 'S' làm tròn đến giây gần nhất. Phần tử 2: 19.999999 giây → 20 giây (làm tròn lên). Phần tử 4: 45.999999 giây → 46 giây (làm tròn lên).