python - 如何在 Pandas 的前后行索引之间有效地取平均值
问题描述
目标是获得给定索引行的 n-preceeding 和 n-succeding 的平均值。
对于给定的索引,获取索引列表的平均值。例如
index index of average
0 0,1,2
1 0,1,2,3
2 0,1,2,3,4
...
9 7,8,9,10,11
10 8,9,10,11,12
这可以实现如下:
import pandas as pd
arr=[[6772],
[7182],
[8570],
[11078],
[11646],
[13426],
[16996],
[17514],
[18408],
[22128],
[22520],
[23532],
[26164],
[26590],
[30636],
[3119],
[32166],
[34774]]
df=pd.DataFrame(arr,columns=['a'])
df['cal']=0
idx_c=2
for idx in range(len(df)):
idx_l=idx-idx_c
idx_t=idx+idx_c
idx_l=0 if idx_l<0 else idx_l
idx_t=len(df) if idx_t>len(df) else idx_t
df.loc[idx,'cal']=df['a'][df.index.isin(range(idx_l,idx_t+1))].mean()
但是,我想知道有没有更有效的方法来完成上述任务?
解决方案
Series.rolling
这里的技巧是使用带有可选参数rolling
的大小窗口来居中滚动计算的结果。例如,如果窗口大小为,滚动计算的结果将存储在位置。2*w + 1
center=True
w=2
2*w + 1 = 5
3
w = 2
df['avg'] = df['a'].rolling(2 * w + 1, center=True, min_periods=1).mean()
print(df)
a avg
0 6772 7508.00
1 7182 8400.50
2 8570 9049.60
3 11078 10380.40
4 11646 12343.20
5 13426 14132.00
6 16996 15598.00
7 17514 17694.40
8 18408 19513.20
9 22128 20820.40
10 22520 22550.40
11 23532 24186.80
12 26164 25888.40
13 26590 22008.20
14 30636 23735.00
15 3119 25457.00
16 32166 25173.75
17 34774 23353.00
推荐阅读
- android - 是否能够处理包含的 xml 内的按钮按下
- java - 我不断得到什么 ClassCastExpection
- python - keras:样本权重多重不平衡输出
- scheme - Racket 中的 SICP Ch5 eceval 编译器:set-cdr!进入引用列表(不是重复)
- python - Python Pygame - 如何为我的游戏添加计时器?
- javascript - 如何将服务器的当前时间戳自动放入 PHP 的 strtotime() 函数中?
- pandas - 如何对多列使用交叉表?
- c# - Telerik radgridview CellFormatting 不稳定
- mysql - 如何使用一列的值来检查另一行的值?
- php - 手动输入地址时保护laravel中的路由