我的DataFrame位于表单中:
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
我需要在TimeWeek,TimeSat和TimeHoli中找到每一行之间的时差,输出必须是
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
我尝试使用(d['TimeWeek']-df['TimeWeek'].shift().fillna(0)
,它会抛出错误:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
可能是因为列中存在':'。我该如何解决这个问题?
答案 0 :(得分:5)
看起来错误是因为数据是字符串形式而不是时间戳。首先将它们转换为时间戳:
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)
答案 1 :(得分:1)
忘掉我刚才说的一切。熊猫有很好的时间解析。
df["TimeWeek"] = pd.to_timedelta(df["TimeWeek"])
(d['TimeWeek']-df['TimeWeek'].shift().fillna(pd.to_timedelta("00:00:00"))
答案 2 :(得分:0)
>>> 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