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

Python Pandas - Trích xuất số micro-giây từ TimeDeltaIndex

Để trích xuất số micro-giây từ mỗi phần tử của TimeDeltaIndex, hãy sử dụng thuộc tính TimedeltaIndex.microseconds.

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 35s 3us 10ns',
    '+22:39:19.999999',
    '2 day 4h 03:08:02.000045',
    '+21:15:45.999999'
])

3. Hiển thị TimedeltaIndex

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

4. Trích xuất micro-giây

print("\nSố micro-giây từ mỗi phần tử...\n", tdIndex.microseconds)

Ví dụ hoàn chỉnh

import pandas as pd

tdIndex = pd.TimedeltaIndex(data=[
    '10 day 5h 2 min 35s 3us 10ns',
    '+22:39:19.999999',
    '2 day 4h 03:08:02.000045',
    '+21:15:45.999999'
])

print("TimedeltaIndex...\n", tdIndex)
print("\nSố micro-giây từ mỗi phần tử...\n", tdIndex.microseconds)
print("\nDataFrame các thành phần của TimeDeltas...\n", tdIndex.components)

Kết quả đầu ra

TimedeltaIndex...
TimedeltaIndex(['10 days 05:02:35.000003010', '0 days 22:39:19.999999',
                '2 days 07:08:02.000045', '0 days 21:15:45.999999'],
               dtype='timedelta64[ns]', freq=None)

Số micro-giây từ TimeDeltaIndex...
Int64Index([3, 999999, 45, 999999], dtype='int64')

DataFrame các thành phần của TimeDeltas...
    days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0    10      5        2       35             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

Giải thích: Thuộc tính microseconds trả về phần micro-giây dư (0-999999) sau khi đã trừ đi ngày, giờ, phút, giây. Nó không phải là tổng số micro-giây của toàn bộ timedelta. Để có tổng micro-giây, hãy dùng tdIndex.total_seconds() * 1_000_000.