Skip to main content
 首页 » 编程设计

python之将缺失日期转发到 Python Pandas Dataframe

2024年12月31日11Terrylee

我有一个填充如下的 Pandas 数据框:

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: Cannot compare type 'Timestamp' with type 'int'

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

我是 Pandas Dataframe 的新手,如有任何帮助,我们将不胜感激!

请您参考如下方法:

你已经非常接近了,你只需要用 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