首页 > 解决方案 > 如何使用时间和日期输入进行过滤和分类

问题描述

我是python新手,正在尝试解决两个问题,希望有人可以帮助我:

  1. 我有一个数据,其中一列是日期格式:
    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'
  1. 我想创建每天和每个班次的销售额总和,结果类似于:
 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 条件和数据透视表,我进行了扩展研究,但目前无法解决。

标签: pythonpandasdatetimeif-statementpivot-table

解决方案


让我们试着找出时间和分配班次。然后在 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'))

推荐阅读