将缺失的日期填充到Python Pandas数据框中

3
我有一个Panda的数据框,填充如下所示:
ref_date    tag
1/29/2010   1
2/26/2010   3
3/31/2010   4
4/30/2010   4
5/31/2010   1
6/30/2010   3
8/31/2010   1
9/30/2010   4
12/31/2010  2

请注意数据中缺失了几个月份(即7、10、11),我希望通过向前填充的方法填补缺失的数据,使其看起来像这样:

ref_date    tag
1/29/2010   1
2/26/2010   3
3/31/2010   4
4/30/2010   4
5/31/2010   1
6/30/2010   3
7/30/2010   3
8/31/2010   1
9/30/2010   4
10/29/2010  4
11/30/2010  4
12/31/2010  2

缺失日期的标记将具有上一个标记。所有日期表示该月的最后一个工作日。
这是我尝试做的:
idx = pd.date_range(start='1/29/2010', end='12/31/2010', freq='BM')
df.ref_date.index = pd.to_datetime(df.ref_date.index)
df = df.reindex(index=[idx], columns=[ref_date], method='ffill')

它给了我错误提示:

类型错误:无法将类型 "Timestamp" 与类型 "int" 进行比较

其中 pd 是 pandas,df 是数据框。

我对 Pandas 数据框不熟悉,所以任何帮助都将不胜感激!


这行代码看起来不正确:df.ref_date.index = pd.to_datetime(df.ref_date.index),应该更像是 df.set_index = ... - Yuca
2个回答

1
你很接近了,只需要使用ref_date设置数据框的索引,将其重新索引为工作日月末索引并在方法中指定ffill,然后重置索引并重新命名回原始状态即可。
# First ensure the dates are Pandas Timestamps.
df['ref_date'] = pd.to_datetime(df['ref_date'])

# Create a monthly index.
idx_monthly = pd.date_range(start='1/29/2010', end='12/31/2010', freq='BM')

# Reindex to the daily index, forward fill, reindex to the monthly index.
>>> (df
     .set_index('ref_date')
     .reindex(idx_monthly, method='ffill')
     .reset_index()
     .rename(columns={'index': 'ref_date'}))
     ref_date  tag
0  2010-01-29  1.0
1  2010-02-26  3.0
2  2010-03-31  4.0
3  2010-04-30  4.0
4  2010-05-31  1.0
5  2010-06-30  3.0
6  2010-07-30  3.0
7  2010-08-31  1.0
8  2010-09-30  4.0
9  2010-10-29  4.0
10 2010-11-30  4.0
11 2010-12-31  2.0

0
感谢之前回答这个问题但又删除了他的回答的人。我得到了解决方案:
df[ref_date] = pd.to_datetime(df[ref_date])
idx = pd.date_range(start='1/29/2010', end='12/31/2010', freq='BM')
df = df.set_index(ref_date).reindex(idx).ffill().reset_index().rename(columns={'index': ref_date})

我的原始解决方案与您期望的输出不匹配,因此我已将其删除。新版本已重新发布。 - Alexander
抱歉,我打了很多错字。非常感谢你的帮助! - Steve D.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接