python - 如何使用时间和日期输入进行过滤和分类
问题描述
我是python新手,正在尝试解决两个问题,希望有人可以帮助我:
- 我有一个数据,其中一列是日期格式:
Date Sales
0 2019-07-01 00:00:00 16.66
1 2019-07-01 02:14:00 17.35
2 2019-07-01 03:17:00 28.78
3 2019-07-01 03:25:00 15.65
24765 2020-03-20 23:13:00 33.21
24766 2020-03-20 23:15:00 36.60
24767 2020-03-20 23:17:00 12.33
我想创建第三列,在其中确定销售发生的转变:
From 8:00 to 16:00 - 'First Shift'
From 16:00 to 00:00 - 'Second Shift'
From 00:00 to 08:00 - 'Third Shift'
- 我想创建每天和每个班次的销售额总和,结果类似于:
Day Shift Total Sales
2019-07-01 First $543.23
2019-07-01 Second $413.87
2019-07-01 Third $301.12
2020-03-14 Third $214.13
我曾经在 Excel 中工作,我正在尝试转换为 python。
在 Excel 中,我会使用 if 条件和数据透视表,我进行了扩展研究,但目前无法解决。
解决方案
让我们试着找出时间和分配班次。然后在 agg 函数中按 Date、Shift 和 sum 分组
#Set datetime component as index
df.set_index('Date', inplace=True)
#Find time between and allocate shift
df.loc[df.between_time('16:00','00:00').any(1).index,'Shift']='Second Shift'
df.loc[df.between_time('00:00','08:00').any(1).index,'Shift']='Third Shift'
df.loc[df.between_time('08:00','16:00').any(1).index,'Shift']='First Shift'
#Groupby date, shift and sum the sales
df.groupby([df.index.date,'Shift']).agg(TotalSales=('Sales', 'sum'))
或者
#Create new column Time
df['Date']=pd.to_datetime(df['Date'])
df['Time']=pd.to_datetime(df['Date']).dt.strftime('%H:%M')
#Allocate Shifts using np.select
c=[df.Time.between('00:00','08:00'),df.Time.between('08:00','16:00'),df.Time.between('16:00','23:59')]
choices=['Third Shift','First Shift','Second Shift']
df['Shift']=np.select(c,choices)
#Groupby and sum
df.groupby([df.Date.dt.date,'Shift']).agg(TotalSales=('Sales', 'sum'))
推荐阅读
- triggers - 在 Firebird 触发器中创建消息提示
- c# - 如何对齐 GUILayout 元素
- python - ''.join() 解析 txt 以在 NLP google API 中识别命名实体时出错
- ios - 每次用户的自动续订订阅续订时如何获得通知
- android - 无法在 Android 操作栏中更改图像宽度和高度
- c# - 如何使 VSCode 显示 c# 的对象和方法定义中的所有可用方法?
- r - 如何使用 dplyr 计算总非 na 值?
- xslt - if then else 或 when-otherwise 的 XSLT 语法
- google-sheets - 如何对 Google 表格中的整个列使用 IF 语句?
- azure - 不使用 FTP 将文件从构建代理复制到应用服务