熊猫重新采样ffill()最后一行

时间:2019-07-20 11:06:05

标签: python pandas resampling

我想每小时对每个年度数据帧重新采样一次,其中包括去年。我该如何有效地做到这一点?

我有以下数据框:

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的所有值。如何有效地做到这一点?

非常感谢!

1 个答案:

答案 0 :(得分:0)

想法是用下一年创建新的最后一个值,并附加到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
相关问题