gpt4 book ai didi

Python Pandas - 周期长度不均匀的移动平均线

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:53 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何处理周期长度不均匀的 Pandas 中的时间序列数据。我要看的第一个例子是如何计算过去 15 天的移动平均线。这是数据的示例(时间是 UTC)

index   date_time         data
46701 1/06/2016 19:27 15.00
46702 1/06/2016 19:28 18.25
46703 1/06/2016 19:30 16.50
46704 1/06/2016 19:33 17.20
46705 1/06/2016 19:34 18.18

我不确定我是否应该只填写数据以使其全部以 1 分钟为增量,或者是否有更聪明的方法...如果有人提出建议,我们将不胜感激

谢谢 - KC

最佳答案

你可以这样做。

  • 以您想要的频率重新采样(或缩减采样)
    • 这里你必须注意重采样策略。它必须与您的数据的含义一致。在这里,我任意使用了 bfill(使用下一个有效值的回填),但另一种策略可能更合适,例如 ffill(传播最后一个有效值的前向填充)。
  • 计算移动平均值。
  • 也许你将不得不处理索引

注意:rolling 的语法已在 pandas 0.18.0 中引入.然而,在以前的版本中使用 pd.rolling_mean 可以做同样的事情。

# Test data
d = {'data': [15.0, 18.25, 16.5, 17.199999999999999, 18.18],
'date_time': ['1/06/2016 19:27',
'1/06/2016 19:28',
'1/06/2016 19:30',
'1/06/2016 19:33',
'1/06/2016 19:34'],
'index': [46701, 46702, 46703, 46704, 46705]}

df = DataFrame(d)
df['date_time'] = pd.to_datetime(df['date_time'])

# Setting the date as the index
df.set_index('date_time', inplace=True)
# Resampling data
df = df.resample('1T').bfill()
# Performing moving average
df['moving'] = df['data'].rolling(window=3, center=True).mean()
df.plot(y=['data', 'moving'])
df
data index moving
date_time
2016-01-06 19:27:00 15.00 46701 NaN
2016-01-06 19:28:00 18.25 46702 16.583333
2016-01-06 19:29:00 16.50 46703 17.083333
2016-01-06 19:30:00 16.50 46703 16.733333
2016-01-06 19:31:00 17.20 46704 16.966667
2016-01-06 19:32:00 17.20 46704 17.200000
2016-01-06 19:33:00 17.20 46704 17.526667
2016-01-06 19:34:00 18.18 46705 NaN

plot

编辑

这是一个缺少数据的例子。

# Random data parameters
num_sample = (0, 100)
nb_sample = 1000
start_date = '2016-06-02'
freq = '2T'

random_state = np.random.RandomState(0)

# Generating random data
df = pd.DataFrame({'data': random_state.randint(num_sample[0], num_sample[1], nb_sample)},
index=random_state.choice(
pd.date_range(start=pd.to_datetime(start_date), periods=nb_sample * 3,
freq=freq),
nb_sample))
# Removing duplicate index
df = df.groupby(df.index).first()
# Removing data for closed periods
df.loc[(df.index.hour >= 22) | (df.index.hour <= 7),'data'] = np.nan
# Resampling
df = df.resample('1T').ffill()
# Moving average by hours
df['avg'] = df['data'].rolling(window=60).mean()

ax = df.plot(kind='line', subplots=True)

enter image description here

关于Python Pandas - 周期长度不均匀的移动平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37577470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com