gpt4 book ai didi

python - 使用 lambda、Pandas 添加 10 行

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

我在以下形式的 pandas 中有一个数据框:

        column
0 0
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
11 66
12 78
13 91
14 105
15 120

任务是每 10 行求和并创建新列来求和。结果应该是这样的数据框:

        num     sum        Description(no need to add this column)
0 0 0 sum of numbers of rows of column "num" by indexes(0)
1 1 1 sum of numbers of rows of column "num" by indexes(0-1)
2 3 4 sum of numbers of rows of column "num" by indexes(0-2)
3 6 10 sum of numbers of rows of column "num" by indexes(0-3)
4 10 20 sum of numbers of rows of column "num" by indexes(0-4)
5 15 35 sum of numbers of rows of column "num" by indexes(0-5)
6 21 56 sum of numbers of rows of column "num" by indexes(0-6)
7 28 84 sum of numbers of rows of column "num" by indexes(0-7)
8 36 120 sum of numbers of rows of column "num" by indexes(0-8)
9 45 165 sum of numbers of rows of column "num" by indexes(0-9)
10 55 220 sum of numbers of rows of column "num" by indexes(1-10)
11 66 285 sum of numbers of rows of column "num" by indexes(2-11)
12 78 360 sum of numbers of rows of column "num" by indexes(3-12)
13 91 445 sum of numbers of rows of column "num" by indexes(4-13)
14 105 540 sum of numbers of rows of column "num" by indexes(5-14)
15 120 645 sum of numbers of rows of column "num" by indexes(6-15)

你能解释一下如何使用 lambda 吗?我试过使用 shift,但没用。

最佳答案

您可以使用 rolling .summin_periods = 1:

df['sum'] = df.column.rolling(10, min_periods=1).sum()
df

enter image description here

关于python - 使用 lambda、Pandas 添加 10 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42722421/

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