【问题标题】:Forward filling missing dates into Python Pandas Dataframe将缺失的日期向前填充到 Python Pandas 数据框中
【发布时间】: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 = ...

标签: python pandas dataframe


【解决方案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

【讨论】:

    【解决方案2】:

    感谢之前回答此问题但删除了他的答案的人。我得到了解决方案:

    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})
    

    【讨论】:

    • 我的原始解决方案与您的预期输出不符,因此我将其删除。新版本已重新发布。
    • 抱歉,我打错了很多字。非常感谢您的帮助!
    猜你喜欢
    • 2021-06-17
    • 2016-11-16
    • 2022-08-15
    • 2018-03-24
    • 2013-10-19
    • 2021-07-22
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    相关资源
    最近更新 更多