Pandas 重新索引以填充缺失的日期,还是更好的填充方法?

2023-12-13

我的数据是工厂的缺勤记录。有些日子没有缺勤,因此没有记录当天的数据或日期。然而,与所示的其他示例相比,这变得很棘手,在任何一天,都可能由于各种原因而出现多次缺勤。数据中的日期与记录的比率并不总是 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

等等。这个想法是所有班次和描述都将具有该时间段内所有日期的值(在此示例中为 2014 年 1 月 1 日 - 2014 年 12 月 31 日)

我读过几个例子,最接近的例子是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')

但是,当我取消注释时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

预先感谢您的帮助,我是新手,两天后没有太大进展。我真的很感激这里的人们如何帮助解答,但最重要的是关于解决方案为何有效的指导。


我认为您只是在使用日期时间时遇到问题,这种方法对我有用

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')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas 重新索引以填充缺失的日期,还是更好的填充方法? 的相关文章

随机推荐