用pandas的rolling函数代替下列语句: data2_0_time3.loc[i,'speed_391_24']=0 data2_0_time3.loc[i,'speed_391_23']=0 data2_0_time3.loc[i,'speed_391_22']=0 k=0 r=len(data2_0_time3)-1-i for j in range(1,4): if np.isnan(data2_0_time3.iat[i-j,0])==False: data2_0_time3.loc[i,'speed_391_24']=data2_0_time3.iat[i,0]+data2_0_time3.iat[i-j,0] data2_0_time3.loc[i,'speed_391_23']=data2_0_time3.iat[i,1]+data2_0_time3.iat[i-j,1] data2_0_time3.loc[i,'speed_391_22']=data2_0_time3.iat[i,2]+data2_0_time3.iat[i-j,2] k=k+1 for j in range(1,r): if np.isnan(data2_0_time3.iat[i+j,0])==False: data2_0_time3.loc[i,'speed_391_24']=data2_0_time3.iat[i,0]+data2_0_time3.iat[i+j,0] data2_0_time3.loc[i,'speed_391_23']=data2_0_time3.iat[i,1]+data2_0_time3.iat[i+j,1] data2_0_time3.loc[i,'speed_391_22']=data2_0_time3.iat[i,2]+data2_0_time3.iat[i+j,2] k=k+1 data2_0_time3.loc[i,'speed_391_24']=data2_0_time3.iat[i,0]/k data2_0_time3.loc[i,'speed_391_23']=data2_0_time3.iat[i,1]/k data2_0_time3.loc[i,'speed_391_22']=data2_0_time3.iat[i,2]/k
时间: 2023-06-08 12:06:41 浏览: 156
对pandas中时间窗函数rolling的使用详解
5星 · 资源好评率100%
可以使用下列代码来代替原有的语句:
```Python
cols = ['speed_391_24', 'speed_391_23', 'speed_391_22']
rolling_df = data2_0_time3.loc[:i][cols].rolling(window=3, min_periods=1)
data2_0_time3.loc[i, cols] = rolling_df.mean().iloc[-1].values
```
这里用到了 rolling() 函数来实现对DataFrame的滚动计算,计算方式采用的是 rolling_df.mean(),然后用 iloc 从中选择最后一行的值进行填充。值得注意的是,这里的 rolling() 函数默认是窗口为3,但是要达到原有语句的效果,还需要加上 min_periods=1 参数。
阅读全文