【问题标题】:Slicing Datetime Function: Python切片日期时间函数:Python
【发布时间】: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


    【解决方案1】:

    让我们使用pd.cut

    pd.cut(s.dt.hour,[-0.001,12,18,24],labels=['Morning','Afternoon','Evening'])
    

    【讨论】:

    • 这行得通 - 谢谢。如果可能的话,有没有办法使上述功能起作用?没有义务回复 - 只是想看看它会是什么样子[更多我自己的学习]
    • @AdrianC between 会直接做过滤而不是返回 bool,所以我会推荐df['visitStartTime_aest'].dt.strftime('%H:%M:%S')>'00:00:00'&df['visitStartTime_aest'].dt.strftime('%H:%M:%S')<'12:00:00
    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2021-12-27
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    相关资源
    最近更新 更多