Pandas 在 Groupby 中重新索引日期
Pandas reindex dates in Groupby
我有一个以零星日期作为索引的数据框,列 = 'id' 和 'num'。我想 pd.groupby
'id' 列,并将重新索引应用于数据框中的每个组。
我的示例数据集如下所示:
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
我在 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
我试过这个,但没有成功:
newdf=df.groupby('id').reindex(method='ffill')
其中 returns 错误:AttributeError: Cannot access callable attribute 'reindex' of 'DataFrameGroupBy' objects, try using the 'apply' method
如有任何帮助,我们将不胜感激
可能有更巧妙的方法来做到这一点,但这个有效:
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)
我有一个以零星日期作为索引的数据框,列 = 'id' 和 'num'。我想 pd.groupby
'id' 列,并将重新索引应用于数据框中的每个组。
我的示例数据集如下所示:
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
我在 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
我试过这个,但没有成功:
newdf=df.groupby('id').reindex(method='ffill')
其中 returns 错误:AttributeError: Cannot access callable attribute 'reindex' of 'DataFrameGroupBy' objects, try using the 'apply' method
如有任何帮助,我们将不胜感激
可能有更巧妙的方法来做到这一点,但这个有效:
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)