Pandas在Groupby中重新编制日期

clg*_*lg4 8 python pandas reindex

我有一个带有零星日期的数据框作为索引,列='id'和'num'.我想要pd.groupby'id'列,并将reindex应用于数据帧中的每个组.

我的示例数据集如下所示:

            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
Run Code Online (Sandbox Code Playgroud)

我的预期输出一次pd.reindex用ffill的是:

            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
Run Code Online (Sandbox Code Playgroud)

我试过这个,除其他外无济于事: newdf=df.groupby('id').reindex(method='ffill') 哪个返回错误:AttributeError: Cannot access callable attribute 'reindex' of 'DataFrameGroupBy' objects, try using the 'apply' method

任何帮助将非常感激

Joe*_*ron 13

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

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)
Run Code Online (Sandbox Code Playgroud)