简体   繁体   中英

How do I get the absolute difference between two datetime.time Pandas columns?

Say I have this dataframe:

import pandas as pd
import datetime

x = [datetime.time(23,0),datetime.time(6,0),datetime.time(18,0),datetime.time(17,0)]
y = [datetime.time(22,0),datetime.time(9,0),datetime.time(9,0),datetime.time(23,0)]

df = pd.DataFrame({'time1':x,'time2':y})

which looks like this: 在此处输入图像描述

How would I compute the absolute difference between the two columns? Subtraction doesn't work. The result should look like this:

df['abs_diff'] = [1,3,9,6]

在此处输入图像描述

Thanks so much!

Pandas doesn't like datetime objects so very much; it labels the series as object dtype, so you can't really do any arithmetics on those. You can convert the data to Pandas' timedelta:

df['abs_diff'] = (pd.to_timedelta(df['time1'].astype(str))   # convert to timedelta
   .sub(pd.to_timedelta(df['time2'].astype(str)))            # then you can subtract
   .abs().div(pd.Timedelta('1H'))                            # and absolute value, and divide
)

Output:

      time1     time2  abs_diff
0  23:00:00  22:00:00       1.0
1  06:00:00  09:00:00       3.0
2  18:00:00  09:00:00       9.0
3  17:00:00  23:00:00       6.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM