gpt4 book ai didi

python - Pandas 数据框中的可变移位

转载 作者:行者123 更新时间:2023-11-28 17:22:26 24 4
gpt4 key购买 nike

import pandas as pd

df = pd.DataFrame({'A':[3,5,3,4,2,3,2,3,4,3,2,2,2,3],
'B':[10,20,30,40,20,30,40,10,20,30,15,60,20,15]})

A B
0 3 10
1 5 20
2 3 30
3 4 40
4 2 20
5 3 30
6 2 40
7 3 10
8 4 20
9 3 30
10 2 15
11 2 60
12 2 20
13 3 15

我想附加一个 C 列,其中包含 B 的滚动平均值(滚动周期 = A)。

例如,row index(2) 处的 C 值应为 df.B.rolling(3).mean() = mean(10 ,20,30)row index(4) 处的 C 值应为 df.B.rolling(2).mean( ) = 均值 (40,20)

最佳答案

可能是愚蠢的慢......但是这就完成了

def crazy_apply(row):
p = df.index.get_loc(row.name)
a = row.A
return df.B.iloc[p-a+1:p+1].mean()

df.apply(crazy_apply, 1)

0 NaN
1 NaN
2 20.000000
3 25.000000
4 30.000000
5 30.000000
6 35.000000
7 26.666667
8 25.000000
9 20.000000
10 22.500000
11 37.500000
12 40.000000
13 31.666667
dtype: float64

解释
apply 遍历每一列或每一行。我们遍历每一行,因为我们使用了参数 axis=1(请参阅 1 作为 apply 调用中的第二个参数)。因此 apply 的每次迭代都会传递一个代表当前行的 pandas 系列对象。当前索引值在行的 name 属性中。行对象的索引与df的列相同。

因此,df.index.get_loc(row.name) 查找保存在 row.name 中的当前索引值的顺序位置。 row.A 是该行的列 A

关于python - Pandas 数据框中的可变移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com