【发布时间】:2018-09-20 18:08:44
【问题描述】:
我有一个 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')
它给了我错误:
TypeError:无法将类型“时间戳”与“int”类型进行比较
pd 是 pandas,df 是数据框。
我是 Pandas Dataframe 的新手,如有任何帮助,我们将不胜感激!
【问题讨论】:
-
这条线在我看来不正确
df.ref_date.index = pd.to_datetime(df.ref_date.index)应该更像df.set_index = ...