Calculate the difference between the "times" rows in a DataFrame Pandas

My DataFrame is in the form:

       TimeWeek   TimeSat  TimeHoli
0      6:40:00   8:00:00   8:00:00
1      6:45:00   8:05:00   8:05:00
2      6:50:00   8:09:00   8:10:00
3      6:55:00   8:11:00   8:14:00
4      6:58:00   8:13:00   8:17:00
5      7:40:00   8:15:00   8:21:00

I need to find the time difference between each line in TimeWeek, TimeSat and TimeHoli, the output should be

TimeWeekDiff   TimeSatDiff  TimeHoliDiff
00:05:00          00:05:00       00:05:00
00:05:00          00:04:00       00:05:00
00:05:00          00:02:00       00:04:00  
00:03:00          00:02:00       00:03:00
00:02:00          00:02:00       00:04:00 

I tried to use (d['TimeWeek']-df['TimeWeek'].shift().fillna(0), it gives an error:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

Perhaps due to the presence of the ":" column. How to resolve this?

+4
source share
3 answers

It seems like an error occurs because the data is in the form of a string instead of a timestamp. First convert them to timestamps:

df2 = df.apply(lambda x: [pd.Timestamp(ts) for ts in x])

, , (, 23:55 00:05 ).

DataFrame:

>>> df2 - df2.shift()
   TimeWeek  TimeSat  TimeHoli
0       NaT      NaT       NaT
1  00:05:00 00:05:00  00:05:00
2  00:05:00 00:04:00  00:05:00
3  00:05:00 00:02:00  00:04:00
4  00:03:00 00:02:00  00:03:00
5  00:42:00 00:02:00  00:04:00

1+ ( NaT):

(df2 - df2.shift()).iloc[1:, :]

NaT :

(df2 - df2.shift()).fillna(0)
+3

, . Pandas -.

df["TimeWeek"] = pd.to_timedelta(df["TimeWeek"])
(d['TimeWeek']-df['TimeWeek'].shift().fillna(pd.to_timedelta("00:00:00"))
+1
>>> import pandas as pd
>>> df = pd.DataFrame({'TimeWeek': ['6:40:00', '6:45:00', '6:50:00', '6:55:00', '7:40:00']})
>>> df["TimeWeek_date"] = pd.to_datetime(df["TimeWeek"], format="%H:%M:%S")
>>> print df
  TimeWeek       TimeWeek_date
0  6:40:00 1900-01-01 06:40:00
1  6:45:00 1900-01-01 06:45:00
2  6:50:00 1900-01-01 06:50:00
3  6:55:00 1900-01-01 06:55:00
4  7:40:00 1900-01-01 07:40:00
>>> df['TimeWeekDiff'] = (df['TimeWeek_date'] - df['TimeWeek_date'].shift().fillna(pd.to_datetime("00:00:00", format="%H:%M:%S")))
>>> print df
  TimeWeek       TimeWeek_date  TimeWeekDiff
0  6:40:00 1900-01-01 06:40:00      06:40:00
1  6:45:00 1900-01-01 06:45:00      00:05:00
2  6:50:00 1900-01-01 06:50:00      00:05:00
3  6:55:00 1900-01-01 06:55:00      00:05:00
4  7:40:00 1900-01-01 07:40:00      00:45:00
0
source

All Articles