【问题标题】:Pandas resample ffill() last row熊猫重新采样 ffill() 最后一行
【发布时间】:2019-07-20 19:12:36
【问题描述】:

我想每小时重新采样一个年度数据帧,其中包括去年。我怎样才能有效地做到这一点?

我有以下数据框:

df2 = pd.DataFrame({'col' : [2, 3]}, index=['2018', '2019']) 
df2.index=  pd.to_datetime(df2.index)    

df2

            col
2018-01-01        2
2019-01-01        3

现在我每小时重新采样一次,并用相应的年度值填充一年中每个小时的值。

df2=df2.resample('h').ffill()
print(df2.head())
print(df2.info())

                        col
    2018-01-01 00:00:00    2
    2018-01-01 01:00:00    2
    2018-01-01 02:00:00    2
    2018-01-01 03:00:00    2
    2018-01-01 04:00:00    2
    <class 'pandas.core.frame.DataFrame'>
    DatetimeIndex: 8761 entries, 2018-01-01 00:00:00 to 2019-01-01 00:00:00
    Freq: H
    Data columns (total 1 columns):
    col    8761 non-null int64
    dtypes: int64(1)
    memory usage: 136.9 KB
    None

我的问题是前向填充在 2019 年的第一个小时停止。我想要一个覆盖全年的前向填充,即填充所有值直到 2019-12-31 23:00:00。如何有效地做到这一点?

非常感谢!

【问题讨论】:

    标签: python pandas resampling


    【解决方案1】:

    想法是在明年创建新的最后一个值,附加到DataFrameresample 并最后删除最后一行:

    df3 = df2.iloc[[-1]].rename(lambda x: x + pd.offsets.YearBegin())
    print (df3)
                col
    2020-01-01    3
    
    df2=df2.append(df3).resample('h').ffill().iloc[:-1]
    print(df2.tail())
                         col
    2019-12-31 19:00:00    3
    2019-12-31 20:00:00    3
    2019-12-31 21:00:00    3
    2019-12-31 22:00:00    3
    2019-12-31 23:00:00    3
    

    【讨论】:

    • 很遗憾没有:(
    猜你喜欢
    • 2021-06-01
    • 2020-08-18
    • 2020-06-08
    • 2022-06-10
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    相关资源
    最近更新 更多