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

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

Sử dụng tham số data để truyền dữ liệu timedelta:

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 mili-giây

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

Ví dụ hoàn chỉnh

import pandas as pd

# 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'
])

# Hiển thị TimeDeltaIndex
print("TimeDeltaIndex...\n", tdIndex)

# Hiển thị thành phần của TimeDeltas
print("\nDataFrame các thành phần của TimeDeltas...\n", tdIndex.components)

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

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

Giải thích: Phép floor làm tròn xuống từng phần tử đến mức độ chính xác mili-giây gần nhất. Các giá trị micro-giây và nano-giây bị loại bỏ hoặc làm tròn xuống về 0.