微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python数据框查找不带for循环的n行滚动斜率

如何解决Python数据框查找不带for循环的n行滚动斜率

我正在尝试访问数据帧的n行并计算均值。目的不是要使用for循环。因为,我的df有3万行,这可能会减慢它的速度。因此,目标是使用熊猫函数计算n行均值。

我的代码

from scipy import stats 
dfx = pd.DataFrame({'A':[10,20,15,30,1.5,0.6,7,0.8,90,10]}) 
n=2 ## n to cover n samples 
cl_id = dfx.columns.tolist().index('A')  ### cl_id for index number of the column for using in .iloc 
l1=['NaN']*n+[stats.linregress(dfx.iloc[x+1-n:x+1,cl_id].tolist(),[1,2])[0] for x in np.arange(n,len(dfx))]
dfx['slope'] = l1
print(dfx)
      A      slope
0  10.0        NaN
1  20.0        NaN  #stats.linregress([20,10],2])[0] is missing here. Why?
2  15.0       -0.2  #stats.linregress([15,20],2])[0] = 0.2
3  30.0  0.0666667  #stats.linregress([30,15],2])[0] = 0.06667
4   1.5 -0.0350877
5   0.6   -1.11111
6   7.0    0.15625
7   0.8   -0.16129
8  90.0  0.0112108
9  10.0    -0.0125

一切正常。有pythonic的方法吗?就像使用rolling()函数等。

解决方法

n = 2
dfx.A.rolling(n).apply(lambda x: stats.linregress(x,x.index+1)[0],raw=False)

输出:

0         NaN
1    0.100000
2   -0.200000
3    0.066667
4   -0.035088
5   -1.111111
6    0.156250
7   -0.161290
8    0.011211
9   -0.012500

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。