【发布时间】:2019-11-23 16:50:17
【问题描述】:
我有一个包含以下列的日期框:
0 2019-06-30 17:31:43
1 2019-06-30 07:07:41
2 2019-06-30 17:11:46
3 2019-06-30 12:13:50
4 2019-06-30 12:13:55
5 2019-06-30 03:01:53
6 2019-06-30 07:22:02
7 2019-06-30 18:12:47
8 2019-06-30 21:38:19
9 2019-06-30 03:01:58
10 2019-06-30 10:06:16
11 2019-06-30 03:46:43
12 2019-06-30 00:44:24
13 2019-06-30 00:44:29
14 2019-06-30 00:44:32
15 2019-06-30 00:44:33
16 2019-06-30 19:32:09
17 2019-06-30 09:09:42
18 2019-06-30 11:52:10
19 2019-06-30 18:30:00
20 2019-06-30 01:26:56
21 2019-06-30 19:29:02
22 2019-06-30 11:54:39
23 2019-06-30 16:54:47
24 2019-06-30 06:00:49
25 2019-06-30 18:51:17
26 2019-06-30 05:54:55
27 2019-06-30 19:22:43
28 2019-06-29 23:06:12
29 2019-06-30 04:26:07
我要的是一个新的专栏,其中包含一天中的时间 [Morning, Afternoon, Evening]。
以下行返回一个布尔值
test['visitStartTime_aest'].dt.strftime('%H:%M:%S').between('00:00:00','12:00:00')
这一行返回一个过滤的数据框并将值更改为早上 [这是我想要的]
test[test['visitStartTime_aest'].dt.strftime('%H:%M:%S').between('00:00:00','12:00:00')] = 'Morning'
这可行,但现在该列混合了dtypes,因此很难转换剩余的时间戳,因为现在有些是str,有些是datetime64[ns]
我尝试了以下方法,但没有成功:
def time_of_day(df, date_col):
df[date_col] = df[df[date_col].dt.strftime('%H:%M:%S').between('00:00:00','12:00:00')] = 'Morning'
df[date_col] = df[df[date_col].dt.strftime('%H:%M:%S').between('12:00:01','18:00:00')] = 'Afternoon'
df[date_col] = df[df[date_col].dt.strftime('%H:%M:%S').between('18:00:01','23:59:59')] = 'Evening'
return df
这完美地执行了第一行,但随后的行遭受与上述相同的命运[混合 dtypes]
我也试过这个,但没有运气:
def time_of_day(df):
if df['visitStartTime_aest'].dt.strftime('%H:%M:%S').between('00:00:00','12:00:00'):
return 'Morning'
elif df['visitStartTime_aest'].dt.strftime('%H:%M:%S').between('12:00:01','18:00:00'):
return 'Afternoon'
else:
return 'Evening'
test.apply(time_of_day, axis=1)
知道我缺少什么吗?或者关于如何执行的任何指导?
谢谢!
【问题讨论】:
标签: python pandas function date time