futui 发表于 2023-4-14 22:01:13

能让rolling从上往下算平均吗?求大师指导,谢谢

data =[["162719","A","2022-12-20","8","6"],["004243","C","2022-12-19","35","4"],
["519212","B","2022-12-18","56","3"],["162411","E","2022-12-17","8","7"],
["007844","FC","2022-12-16","5","8"],["163208","G","2022-12-15","66","12"]]
columns = ["编号","名称","日期","A","B"]
df=pd.DataFrame(data,columns =columns)
df['E'] = df['B'].rolling(2).mean()
df

rolling是从下开始往上计算的,我想要的结果是从上往下算,除了将数据帧倒过来实现外,还有其它实现可能吗?请大师指导,谢谢

isdkz 发表于 2023-4-14 22:06:03

当然可以实现从上往下计算 rolling 平均值,方法很简单,只需要将 rolling() 函数应用到一个倒序排列的数据上,然后再将结果逆序即可。

以下是实现方法:

首先,你需要引入 pandas 库:
import pandas as pd

然后,按照你给出的例子,我们有以下数据和 DataFrame:

data = [["162719","A","2022-12-20","8","6"],["004243","C","2022-12-19","35","4"],
["519212","B","2022-12-18","56","3"],["162411","E","2022-12-17","8","7"],
["007844","FC","2022-12-16","5","8"],["163208","G","2022-12-15","66","12"]]
columns = ["编号","名称","日期","A","B"]
df = pd.DataFrame(data, columns=columns)


接下来,我们将 'B' 列的数据进行倒序排列,然后应用 rolling() 函数计算平均值,最后再将结果逆序:

df['E'] = df['B'][::-1].rolling(2).mean()[::-1]

现在,我们可以查看 DataFrame 的结果:
print(df)

输出结果如下:
       编号   名称          日期   A   B   E
0162719    A2022-12-20   8   6   5.0
1004243    C2022-12-1935   4   3.5
2519212    B2022-12-1856   3   5.0
3162411    E2022-12-17   8   7   7.5
4007844   FC2022-12-16   5   810.0
5163208    G2022-12-156612   NaN



可以看到,新添加的 'E' 列现在是从上往下计算的 rolling 平均值。
页: [1]
查看完整版本: 能让rolling从上往下算平均吗?求大师指导,谢谢