pandas 在Groupby中重新编制索引的日期 [英] Pandas reindex dates in Groupby

查看:109
本文介绍了 pandas 在Groupby中重新编制索引的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中零星的日期作为索引,并且columns ='id'和'num'.我想pd.groupby'id'列,然后将重新索引应用于数据框中的每个组.

I have a dataframe with sporadic dates as the index, and columns = 'id' and 'num'. I would like to pd.groupby the 'id' column, and apply the reindex to each group in the dataframe.

我的样本数据集如下:

            id  num
2015-08-01  1   3
2015-08-05  1   5
2015-08-06  1   4
2015-07-31  2   1
2015-08-03  2   2
2015-08-06  2   3

ffill一起使用pd.reindex后,我的预期输出是:

My expected output once pd.reindex with ffill is:

            id  num
2015-08-01  1   3
2015-08-02  1   3
2015-08-03  1   3
2015-08-04  1   3
2015-08-05  1   5
2015-08-06  1   4
2015-07-31  2   1
2015-08-01  2   1
2015-08-02  2   1
2015-08-03  2   2
2015-08-04  2   2
2015-08-05  2   2
2015-08-06  2   3

除其他外,我尝试了以下方法: newdf=df.groupby('id').reindex(method='ffill') 返回错误:AttributeError: Cannot access callable attribute 'reindex' of 'DataFrameGroupBy' objects, try using the 'apply' method

I have tried this, among other things to no avail: newdf=df.groupby('id').reindex(method='ffill') Which returns error:AttributeError: Cannot access callable attribute 'reindex' of 'DataFrameGroupBy' objects, try using the 'apply' method

任何帮助将不胜感激

推荐答案

可能有一种更轻松的方式来做到这一点,但这可行:

There's probably a slicker way to do this but this works:

def reindex_by_date(df):
    dates = pd.date_range(df.index.min(), df.index.max())
    return df.reindex(dates).ffill()

df.groupby('id').apply(reindex_by_date).reset_index(0, drop=True)

这篇关于 pandas 在Groupby中重新编制索引的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆