Pyt*_*_DK 4 python python-3.x pandas pandas-groupby
我的数据是工厂的缺勤记录。有些日子没有缺席,因此没有记录当天的数据或日期。但是,在显示的其他示例中,这变得令人毛骨悚然,在任何一天,由于各种原因可能会有几次缺席。数据中的日期与记录的比率并不总是 1 比 1。
我希望的结果是这样的:
(index) Shift Description Instances (SUM)
01-01-14 2nd Baker Discipline 0
01-01-14 2nd Baker Vacation 0
01-01-14 1st Cooks Discipline 0
01-01-14 1st Cooks Vacation 0
01-02-14 2nd Baker Discipline 4
01-02-14 2nd Baker Vacation 3
01-02-14 1st Cooks Discipline 3
01-02-14 1st Cooks Vacation 3
Run Code Online (Sandbox Code Playgroud)
等等。这个想法是所有班次和描述都将具有时间段内所有天的值(在本例中为 1/1/2014 - 12/31/2014)
我已经阅读了几个例子,我最接近这个工作的是here。
ts = pd.read_csv('Absentee_Data_2.csv'
, encoding = 'utf-8'
,parse_dates=[3]
,index_col=3
,dayfirst=True
)
idx = pd.date_range('01.01.2009', '12.31.2017')
ts.index = pd.DatetimeIndex(ts.index)
# ts = ts.reindex(idx, fill_value='NaN')
df = pd.DataFrame(index = idx)
df1 = df.join(ts, how='left')
Run Code Online (Sandbox Code Playgroud)
但是,当我取消注释时,ts = ts.reindex(idx, fill_value='NaN')
会收到错误消息。我已经尝试了至少 10 种其他方法来完成我想要做的事情,所以我不能 100% 确定这是正确的道路,但它似乎让我最接近任何一种进步。
以下是一些示例数据:
Description Unexcused Instances Date Shift
Discipline FALSE 1 Jan 2 2014 2nd Baker
Vacation TRUE 2 Jan 2 2014 1st Cooks
Discipline FALSE 3 Jan 2 2014 2nd Baker
Vacation TRUE 1 Jan 2 2014 1st Cooks
Discipline FALSE 2 Apr 8 2014 2nd Baker
Vacation TRUE 3 Apr 8 2014 1st Cooks
Discipline FALSE 1 Jun 1 2014 2nd Baker
Vacation TRUE 2 Jun 1 2014 1st Cooks
Discipline FALSE 3 Jun 1 2014 2nd Baker
Vacation TRUE 1 Jun 1 2014 1st Cooks
Vacation TRUE 2 Jul 5 2014 1st Cooks
Discipline FALSE 3 Jul 5 2014 2nd Baker
Vacation TRUE 2 Dec 3 2014 1st Cooks
Run Code Online (Sandbox Code Playgroud)
提前感谢您的帮助,我是新手,2 天后没有太大进展。我非常感谢这里的人们如何帮助回答问题,但最重要的是关于解决方案为何有效的说明。像我这样的新手非常感谢分享的智慧。
我认为您只是在使用 datetime 时遇到问题,这种方法对我有用
ts.set_index(['Date'],inplace=True)
ts.index = pd.to_datetime(ts.index,format='%b %d %Y')
d2 = pd.DataFrame(index=pd.date_range('2014-01-01','2014-12-31'))
print ts.join(d2,how='right')
Run Code Online (Sandbox Code Playgroud)