gpt4 book ai didi

python - 如何反转滚动总和?

转载 作者:太空宇宙 更新时间:2023-11-03 13:11:13 25 4
gpt4 key购买 nike

我有一个在分组数据框上计算的滚动总和,但它的加法是错误的,它是 future 的总和,而我需要过去的总和。

我在这里做错了什么?

我导入数据并按维度和日期排序(我已经尝试删除日期排序)

df = pd.read_csv('Input.csv', parse_dates=True)
df.sort_values(['Dimension','Date'])
print(df)

然后我创建一个新列,它是一个按滚动窗口分组的多索引

new_column = df.groupby('Dimension').Value1.apply(lambda x: 
x.rolling(window=3).sum())

然后我将索引重置为与原始索引相同

df['Sum_Value1'] = new_column.reset_index(level=0, drop=True)
print(df)

我也试过在计算前反转索引,但也失败了。

输入

Dimension,Date,Value1,Value2
1,4/30/2002,10,20
1,1/31/2002,10,20
1,10/31/2001,10,20
1,7/31/2001,10,20
1,4/30/2001,10,20
1,1/31/2001,10,20
1,10/31/2000,10,20
2,4/30/2002,10,20
2,1/31/2002,10,20
2,10/31/2001,10,20
2,7/31/2001,10,20
2,4/30/2001,10,20
2,1/31/2001,10,20
2,10/31/2000,10,20
3,4/30/2002,10,20
3,1/31/2002,10,20
3,10/31/2001,10,20
3,7/31/2001,10,20
3,1/31/2001,10,20
3,10/31/2000,10,20

输出:

    Dimension        Date  Value1  Value2  Sum_Value1
0 1 4/30/2002 10 20 NaN
1 1 1/31/2002 10 20 NaN
2 1 10/31/2001 10 20 30.0
3 1 7/31/2001 10 20 30.0
4 1 4/30/2001 10 20 30.0
5 1 1/31/2001 10 20 30.0
6 1 10/31/2000 10 20 30.0
7 2 4/30/2002 10 20 NaN
8 2 1/31/2002 10 20 NaN
9 2 10/31/2001 10 20 30.0
10 2 7/31/2001 10 20 30.0
11 2 4/30/2001 10 20 30.0
12 2 1/31/2001 10 20 30.0
13 2 10/31/2000 10 20 30.0

目标输出:

    Dimension        Date  Value1  Value2  Sum_Value1
0 1 4/30/2002 10 20 30.0
1 1 1/31/2002 10 20 30.0
2 1 10/31/2001 10 20 30.0
3 1 7/31/2001 10 20 30.0
4 1 4/30/2001 10 20 30.0
5 1 1/31/2001 10 20 NaN
6 1 10/31/2000 10 20 NaN
7 2 4/30/2002 10 20 30.0
8 2 1/31/2002 10 20 30.0
9 2 10/31/2001 10 20 30.0
10 2 7/31/2001 10 20 30.0
11 2 4/30/2001 10 20 30.0
12 2 1/31/2001 10 20 Nan
13 2 10/31/2000 10 20 NaN

最佳答案

你需要一个反向求和,因此在求和之前反转你的序列:

lambda x: x[::-1].rolling(window=3).sum()

关于python - 如何反转滚动总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43101652/

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