用前一天的等效值填充缺失数据

Fill missing data with equivalent value from the day before

我有一个数据框,里面全是每小时的数据,其中有缺失值。日期作为索引,布局为 yyyy-mm-dd hh:mm.

对于我工作的上下文,简单地反映上面的值是不合适的。因此 ffill 是不够的。最好反映前一天同一小时的值。

因此,如果前一天 10:00 的值为 "red",则丢失的数据将以 "red" 的值归档。

如果有人能帮助我做到这一点,他们会让我开心! :)

Date Time          |        Yeovilton
01/01/2012 00:00   |           12.4
01/01/2012 01:00   |           11.7
...
...
02/01/2012 00:00   |           5.9
01/01/2012 01:00   |           NaN

按小时对数据进行分组并填写分组:

ts.groupby(ts.index.hour).fillna(method='ffill')

您的问题是,正如您指出的那样,ffill 按顺序运行,您的数据不在您想要填充的顺序中。但是由于您的索引已经是一个时间戳,您可以很容易地提取小时,对其进行分组,然后填充到组中。

为了证明这是有效的(并展示如何为此制作示例数据):

import pandas as pd
import numpy as np

timestamps = [pd.Timestamp(t) for t in ['2011-01-01 10:00:00', '2011-01-01 12:00:00', '2011-01-02 10:00:00']]
colors = ['red', 'blue', np.nan]
ts = pd.Series(colors, index=timestamps)

print ts

# 2011-01-01 10:00:00     red
# 2011-01-01 12:00:00    blue
# 2011-01-02 10:00:00     NaN
# dtype: object

print ts.ffill()

# 2011-01-01 10:00:00     red
# 2011-01-01 12:00:00    blue
# 2011-01-02 10:00:00    blue
# dtype: object

print ts.groupby(ts.index.hour).ffill()

# 2011-01-01 10:00:00     red
# 2011-01-01 12:00:00    blue
# 2011-01-02 10:00:00     red
# dtype: object