python - 将 pandas 时间序列重新采样到预定义的网格

标签 python pandas time-series

假设我有一个如下构建的每周时间序列:

rng = pd.date_range('1/1/2011', periods=72, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
weekly = ts.resample('W').mean()

您还有另一个系列,每天间隔一次,您也希望每周聚合一次,但要以与第一个系列相匹配的方式。

rng2 = pd.date_range('17/1/2011', periods=72, freq='D')
ts2 = pd.Series(np.random.randn(len(rng2)), index=rng2)

请注意,第二个系列不会在同一日期开始,因此只需重新采样 ts2 就会使两个每周系列不一致。如果重新采样可以接收到重新采样的时间索引,那就太好了,但据我所知这是不可能的。

你会怎么做?

最佳答案

@FLab 的答案是最好的,如果你想在两个系列上使用完全相同的索引,你也可以这样做:

import pandas as pd
import numpy as np

rng = pd.date_range('1/1/2011', periods=72, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
weekly = ts.resample('W').mean()

rng2 = pd.date_range('17/1/2011', periods=72, freq='D')
ts2 = pd.Series(np.random.randn(len(rng2)), index=rng2)

ts2.reindex(ts.index).resample('W').mean()

Out[14]: 
2011-01-02         NaN
2011-01-09         NaN
2011-01-16         NaN
2011-01-23   -0.073253
2011-01-30   -0.065030
2011-02-06   -0.037297
2011-02-13    0.101782
2011-02-20   -0.386027
2011-02-27    0.131906
2011-03-06    0.107101
2011-03-13   -0.030496
Freq: W-SUN, dtype: float64

如果您无权访问先前的索引,只需使用 @FLab 方法,例如:

ts.resample('W-SUN').mean()
ts2.resample('W-SUN').mean()

您可以在此处传递多个参数:

Alias   Description
W-SUN   weekly frequency (sundays). Same as ‘W’
W-MON   weekly frequency (mondays)
W-TUE   weekly frequency (tuesdays)
W-WED   weekly frequency (wednesdays)
W-THU   weekly frequency (thursdays)
W-FRI   weekly frequency (fridays)
W-SAT   weekly frequency (saturdays)

关于python - 将 pandas 时间序列重新采样到预定义的网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42951719/

相关文章:

python - 在数据框中显示重复值 -> 键错误

python - 如何用 NaN 计算每行的最佳拟合线?

python - 如何在 Python 中识别 ARIMA 模型的 p(滞后阶数)

python - 选择以特定索引值开头的 Pandas 数据框中的行

python - 如何在 statsmodels 中使用 gamma GLM 的尺度和形状参数

python - 我可以强制 numpy ndarray 获取其内存的所有权吗?

python - 在 python 中将字典转换为 key=value 连接字符串的智能方法

javascript - 等效于 Python 的内容十六进制编码的 CryptoJS SHA512 哈希值?

python - 将 .csv 文件读取到 Pandas 错误 : ',' expected after '"'

android - achartengine 清除 XYMultipleSeriesRenderer 中的渲染器