gpt4 book ai didi

python - 使用 Pandas 绘图

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

我在列表中有一些事件时间,我想绘制它们的指数加权移动平均值。我可以使用以下代码执行此操作。

import numpy as np
import matplotlib.pyplot as plt

print "Code runnning"
a=0.01
l = [3.0,7.0,10.0,20.0,200.0]
y = np.zeros(1000)
for item in l:
y[item]=1
s = np.zeros(1000)
x = np.linspace(0,1000,1000)
for i in xrange(1000):
s[i] = a*y[i-1]+(1-a)*s[i-1]
plt.plot(x, s)
plt.show()

然而,这显然是一种使用 python 的可怕方式。这样做的正确方法是什么?是否可以在不制作所有这些额外的稀疏数组的情况下做到这一点?

输出应该是这样的。

enter image description here

最佳答案

Pandas想到这个任务:

import pandas as pd

l = [3.0,7.0,10.0,20.0,200.0]
s = pd.Series(np.ones_like(l), index=l)
y = s.reindex(range(1000), fill_value=0)
pd.ewma(y, 199).plot()

周期 199 与您的参数 alpha 0.01 相关,如 n=2/(a+1)。结果: enter image description here

关于python - 使用 Pandas 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320688/

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