python - Pandas 重新采样 ffill() 最后一行

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

非常感谢!

最佳答案

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

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

关于python - Pandas 重新采样 ffill() 最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57124147/

相关文章:

python - 类型错误 : __init__() got multiple values for keyword argument 'encoding'

python - Dataframe 为一列选择 Max 但输出另一列的值

python - 计算重复值、删除重复项并保留计数和其他列

python - 使用重采样计算 2 周的平均计数

audio - 如何进行单声道到立体声的转换?

python - Pandas ,.resample ('B' 的意外行为)

python - 使用opencv和python的人脸检测精度

python - Django - 如何使用 URL 中定义的外键创建 POST?

python - 在数组中搜索关键字-python

pandas 按子组的平均值划分组