簡體   English   中英

pandas計算前N個數據幀行的rolling_std

[英]pandas calculate rolling_std of top N dataframe rows

我有這樣的數據幀:

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_std用於執行此操作,但是, 如何動態更改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

它可以通過調用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 ,這允許你傳遞param axis=1這樣你可以逐行調用你的函數,然后你可以訪問index屬性,這就是name和列名屬性,即index ,這允許您切片df來計算滾動std

您可以向func添加窗口arg以根據需要修改窗口

編輯

看起來您的索引是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM