Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算前N个数据帧行的滚动标准_Python_Pandas - Fatal编程技术网

Python 计算前N个数据帧行的滚动标准

Python 计算前N个数据帧行的滚动标准,python,pandas,Python,Pandas,我有这样一个数据帧: 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行的std,例如: 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

我有这样一个数据帧:

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行的std,例如:

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\u std用于实现这一点,但是,如何动态更改N?

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


索引:75项,2015-04-16至2015-07-31
数据列(共4列):
75个非空浮点64
数据类型:float64(4)
内存使用率:2.9+KB

可以在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
,以便您可以按行调用函数,然后您可以访问index属性,即
name
和column name属性,即
index
,这允许您对df进行切片以计算滚动
std

您可以将窗口参数添加到
func
以根据需要修改窗口

编辑

看起来您的索引是一个str,以下操作应该有效:

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
不能连接'str'和'int'对象“
name
是索引属性,你能从
df.info()
发布输出并将其编辑到你的问题中吗,你的索引是什么?我有一个编辑问题。我需要计算列'fluc_ic'好的,看起来你的索引实际上是一个日期str,我会更新我的答案
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