pandas 中 resample 和 asfreq 的不同行为

Different behaviour with resample and asfreq in pandas

我有一个这样的数据框:

                            A        B    value
2014-11-14 12:00:00      30.5    356.3      344
2014-11-15 00:00:00      30.5    356.3      347
2014-11-15 12:00:00      30.5    356.3      356
2014-11-16 00:00:00      30.5    356.3      349
...
2017-01-06 00:00:00      30.5    356.3      347

而且我想确保从头到尾都没有遗漏时间(即,索引从 12 小时到 12 小时没有更大的跳跃)。如果缺少日期,例如,如果缺少值,例如 2015-12-12 12:00:00 我想添加这样一行:

...
2015-12-12 00:00:00     30.5    356.3    323
2015-12-12 12:00:00     30.5    356.3    NaN  *<- add this*
2015-12-13 00:00:00     30.5    356.3    347

@ted-petrou 在此处 解决了如何操作的问题。解决方案是:

df1= df.asfreq('12H')
df1[['A','B']] = df1[['A','B']].fillna(method='ffill')

我的问题: 我可以用 resample 代替 asfreq 吗?正在做

df1= df.resample('12H')
df1[['A','B']] = df1[['A','B']].fillna(method='ffill')

我得到 ValueError: cannot set items on DatetimeIndexResampler。我不明白为什么。对于这种特殊情况,resampleasfreq 不是相同的操作吗?我错过了什么?提前谢谢你。

请记住,DF.resample() 是一个 time-based groupby,它的每个组都必须跟一个缩减方法。

所以简单地使用它只会初始化 Resampler 就像调用 DF.rolling() 方法时发生的那样。两者在这里的行为相似:

df[['A', 'B']].resample('12H')
DatetimeIndexResampler [freq=<12 * Hours>, axis=0, closed=left, label=left, convention=start, base=0]

您需要指定一个 聚合函数 以使其具有用于计算组的度量。

为了针对您的情况执行此操作:

1) 在两列上使用 .resample().ffill(),然后将它们与第三列连接起来。当然,由于第 3 个没有重新采样,它们将由 NaNs.

填充
df[['A', 'B']].resample('12H').ffill().join(df['value'])

2) 使用 .resample().asfreq() 作为其 aggfunc 类似于您所做的:

df1 = df.resample('12H').asfreq()
df1[['A','B']] = df1[['A','B']].fillna(method='ffill')

注:这里使用.asfreq()可能比.resample更适合变频,如果最终目标不是聚合组。