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

So sánh Timestamp cụ thể trong DataFrame Pandas – Python

Giới thiệu

Để so sánh các timestamp cụ thể (theo vị trí hàng) giữa hai cột datetime trong DataFrame, truy cập bằng index số nguyên [i] và tính hiệu tuyệt đối.

Ví dụ minh họa

import pandas as pd

# DataFrame với 2 cột Timestamp
dataFrame = pd.DataFrame(
    {
        "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],
        "Date_of_Purchase": [
            pd.Timestamp("2021-06-10"),
            pd.Timestamp("2021-07-11"),
            pd.Timestamp("2021-06-25"),
            pd.Timestamp("2021-06-29"),
            pd.Timestamp("2021-03-20")
        ],
        "Date_of_Service": [
            pd.Timestamp("2021-11-05"),
            pd.Timestamp("2021-12-03"),
            pd.Timestamp("2021-10-30"),
            pd.Timestamp("2021-11-29"),
            pd.Timestamp("2021-08-20")
        ]
    }
)
print("DataFrame...\n", dataFrame)

# So sánh 3 hàng đầu (index 0,1,2)
timestamp1_diff = abs(dataFrame['Date_of_Purchase'][0] - dataFrame['Date_of_Service'][0])
timestamp2_diff = abs(dataFrame['Date_of_Purchase'][1] - dataFrame['Date_of_Service'][1])
timestamp3_diff = abs(dataFrame['Date_of_Purchase'][2] - dataFrame['Date_of_Service'][2])

print("\nChênh lệch Xe 1 (Purchase - Service):", timestamp1_diff)
print("Chênh lệch Xe 2:", timestamp2_diff)
print("Chênh lệch Xe 3:", timestamp3_diff)

Kết quả đầu ra

DataFrame...
      Car Date_of_Purchase Date_of_Service
0   Audi       2021-06-10      2021-11-05
1  Lexus       2021-07-11      2021-12-03
2  Tesla       2021-06-25      2021-10-30
3 Mercedes       2021-06-29      2021-11-29
4    BMW       2021-03-20      2021-08-20

Chênh lệch Xe 1 (Purchase - Service): 148 days 00:00:00
Chênh lệch Xe 2: 145 days 00:00:00
Chênh lệch Xe 3: 127 days 00:00:00

Lưu ý: Truy cập df['col'][i] là chaining indexing, khuyến khích dùng df.iloc[i]['col'] hoặc df.loc[i, 'col'] (nếu index là số).