python - 使用 Python 计算持续时间/ session 的时间

标签 python pandas

我有 1 个带有日期和时间的 pandas 数据框。我想再添加 1 个名为“ session ”的列,其值为上午、下午、晚上、晚上。

   Time
   2016-07-10 01:18:00
   2016-07-10 11:21:00
   2016-07-10 17:29:00
   2016-07-10 21:43:00

我想要像这样的输出

   Time                     Session
   2016-07-10 01:18:00      Night
   2016-07-10 11:21:00      Morning
   2016-07-10 17:29:00      Afternoon
   2016-07-10 21:43:00      Evening

如何做到这一点?

我通过定义中断来尝试这个

00:00 - 06:00 Night
06:00 - 12:00 Morning
12:00 - 18:00 Afternoon
18:00 -23:59 Evening


df.Time[(df.Time.dt.hour < 6) | (df.Time.dt.hour > 0) | (df.Time.dt.minute < 59) | (df.Time.dt.minute > 0)] = "Night"

但它无法正常工作。提前致谢

最佳答案

使用 pd.cut 为 session 标签创建容器。

df.assign(session=pd.cut(df.Time.dt.hour,[0,6,12,18,24],labels=['Night','Morning','Afternoon','Evening']))

输出:

                 Time    session
0 2016-07-10 01:18:00      Night
1 2016-07-10 11:21:00    Morning
2 2016-07-10 17:29:00  Afternoon
3 2016-07-10 21:43:00    Evening

关于python - 使用 Python 计算持续时间/ session 的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43893002/

相关文章:

python - 通过连接 Pandas 中的行的数据帧 header

python - tkinter 中的鼠标滚轮 + 滚动条出现问题

python - 如何根据日期列的 1 年滞后创建新的指标列?

python - 在数据框中使用 isin 和 NaN

python - calendar.monthrange() - ValueError : The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

python - 拆分非常大的 Pandas 数据框,替代 Numpy array_split

python - 原生 TF 与 Keras TF 性能比较

python - Django:CSV 模型导入

python - 更改数据框中多个位置的最快方法

python - 克服 Ashton String 任务中的 MemoryError/Slow Runtime