python - pandas 中 resample 和 asfreq 的不同行为

标签 python pandas resampling

我有一个像这样的数据框:

                            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

如何做的问题在这里解决了 Resampling dataframe in pandas as a checking operation作者:@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:无法在 DatetimeIndexResampler 上设置项目。我不明白为什么。对于这种特殊情况,resampleasfreq 操作不是相同吗?我缺少什么?预先感谢您。

最佳答案

请记住,DF.resample() 是一个基于时间的分组,必须在每个组上遵循缩减方法。

因此,简单地使用它只会初始化 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(),然后将它们与第三列连接起来。当然,由于第三个没有重新采样,它们将由 NaN 填充。

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 更适合频率转换,如果最终目标不是聚合群体。

关于python - pandas 中 resample 和 asfreq 的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41612641/

相关文章:

python - Python 中的类用法

python - 在 Scrapy 中利用 Beautifulsoup

python - 对 pandas 数据框进行分组,然后通过聚合取abs的平均值

python - 如何将类型为 "object"的时间戳列转换为正确的 "time"类型?

python - 套接字错误 - python

Python语音识别API响应很慢

python - 将连续变量下采样到均匀分布

python - Pandas OHLCV 转 JSON 格式

python - 如何使用 Pandas 计算数据框中的类标签频率?

machine-learning - 训练测试拆分后不平衡数据的欠采样