Pandas计算前N行数据的滚动标准差

3

I have a dataframe like this:

date      A
2015.1.1  10
2015.1.2  20
2015.1.3  30
2015.1.4  40
2015.1.5  50
2015.1.6  60

我需要计算前N行的标准差,例如:

date      A  std
2015.1.1  10  std(10)
2015.1.2  20  std(10,20)
2015.1.3  30  std(10,20,30)
2015.1.4  40  std(10,20,30,40)
2015.1.5  50  std(10,20,30,40,50)
2015.1.6  60  std(10,20,30,40,50,60)

可以使用pd.rolling(window=N).std来计算,其中N是滚动窗口的大小。如果想要动态更改N的值,可以将N存储在变量中并随时更改。

df[['A']].apply(lambda x:pd.rolling_std(x,N))

<class 'pandas.core.frame.DataFrame'>
Index: 75 entries, 2015-04-16 to 2015-07-31
Data columns (total 4 columns):
A    75 non-null float64
dtypes: float64(4)
memory usage: 2.9+ KB
1个回答

1

可以通过在df上调用apply来实现:

In [29]:
def func(x):
    return df.iloc[:x.name + 1][x.index].std()
​
df['std'] = df[['A']].apply(func, axis=1)
df
Out[29]:
       date   A        std
0  2015.1.1  10        NaN
1  2015.1.2  20   7.071068
2  2015.1.3  30  10.000000
3  2015.1.4  40  12.909944
4  2015.1.5  50  15.811388
5  2015.1.6  60  18.708287

这里使用了双下标[[]]来对只有一列的df调用apply,这允许你传递参数axis=1以便按行调用函数,然后可以访问索引属性和列名属性,分别是nameindex,这使得你可以切片你的df计算滚动窗口的std
你可以添加一个窗口参数到func中以根据需要修改窗口大小。 编辑: 看起来你的索引是字符串,下面的代码应该可以工作:
In [39]:
def func(x):
    return df.ix[:x.name ][x.index].std()
​
df['std'] = df[['A']].apply(lambda x: func(x), axis=1)
df

Out[39]:
           A        std
date                   
2015.1.1  10        NaN
2015.1.2  20   7.071068
2015.1.3  30  10.000000
2015.1.4  40  12.909944
2015.1.5  50  15.811388
2015.1.6  60  18.708287

x.name + 1 的意思是什么? - seizetheday
“name” 是索引属性,请问您能否发布 df.info() 的输出并将其编辑到您的问题中,您的索引是什么? - EdChum
我已经编辑了问题。我需要计算“fluc_ic”列。 - seizetheday
好的,看起来你的索引实际上是一个日期字符串,我会更新我的答案。 - EdChum
它有效。ixiloc之间有什么区别? - seizetheday
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接