我有一个 pandas 系列,就像这样,
data = [1,2,3,2,4,5,6,3,5]
ds = pd.Series(data)
print (ds)
0 1
1 2
2 3
3 2
4 4
5 5
6 6
7 3
8 5
我有兴趣获得每个指数的标准差。例如,当我处于索引 5 时,我想计算 ds[0:4]
的标准差。
我已经使用以下代码完成了此操作,
df = pd.DataFrame(columns = ['data', 'avreturns', 'sd'])
df.data = data
for i in df.index:
dataslice = df.ix[0:i]
df['avreturns'].loc[i] = dataslice.data.mean()
df['sd'].loc[i] = dataslice.data.std()
print (df)
data avreturns sd
0 1 1 NaN
1 2 1.5 0.7071068
2 3 2 1
3 2 2 0.8164966
4 4 2.4 1.140175
5 5 2.833333 1.47196
6 6 3.285714 1.799471
7 3 3.25 1.669046
8 5 3.444444 1.666667
这可行,但我使用循环并且速度很慢。有没有办法对其进行矢量化?
我能够使用 cumsum()
函数对平均值计算进行矢量化:
df.data.cumsum()/(df.index+1)
有没有办法对标准差计算进行矢量化?
最佳答案
您可能对 pd.expanding_std
感兴趣,它可以为您计算累积标准差:
>>> pd.expanding_std(ds)
0 NaN
1 0.707107
2 1.000000
3 0.816497
4 1.140175
5 1.471960
6 1.799471
7 1.669046
8 1.666667
dtype: float64
就其值(value)而言,这种类型的累积运算向量化可能非常繁琐:the Pandas implementation似乎使用 Cython 循环来提高速度。
关于python - pandas 数据系列的矢量化标准差计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27974221/