如何逐行计算 Python 中数据框的小计?
How to calculate subtotals, line by line of a Data Frame in Python?
我有以下DF:
import pandas as pd
df = pd.DataFrame([['2020/01/01','A',5],['2020/01/10','B',-2],['2020/01/15','C',3],['2020/01/18','B',9]],columns=['datetime','broker','amount'])
我需要逐行计算新列中 "amount" 列的小计...
我已经尝试过以下代码:
df['Subtotal amount'] = df.sum(axis=1, numeric_only=True)
其中returns结果如下:
datetime broker amount Subtotal amount
0 2020/01/01 A 5 5
1 2020/01/10 B -2 -2
2 2020/01/15 C 3 3
3 2020/01/18 B 9 9
但我希望结果是逐行计算的,加上和减去前面几行的值:
datetime broker amount Subtotal amount
0 2020/01/01 A 5 5
1 2020/01/10 B -2 3
2 2020/01/15 C 3 6
3 2020/01/18 B 9 15
正如 Andrej Kesely 在评论中提出的那样,您正在尝试进行累积求和。 cumsum 是你想要的 numpy 函数。这应该可以解决问题。
df['Subtotal amount'] = df.amount.cumsum()
感谢 Andrej,我只是将其移至答案
我有以下DF:
import pandas as pd
df = pd.DataFrame([['2020/01/01','A',5],['2020/01/10','B',-2],['2020/01/15','C',3],['2020/01/18','B',9]],columns=['datetime','broker','amount'])
我需要逐行计算新列中 "amount" 列的小计... 我已经尝试过以下代码:
df['Subtotal amount'] = df.sum(axis=1, numeric_only=True)
其中returns结果如下:
datetime broker amount Subtotal amount
0 2020/01/01 A 5 5
1 2020/01/10 B -2 -2
2 2020/01/15 C 3 3
3 2020/01/18 B 9 9
但我希望结果是逐行计算的,加上和减去前面几行的值:
datetime broker amount Subtotal amount
0 2020/01/01 A 5 5
1 2020/01/10 B -2 3
2 2020/01/15 C 3 6
3 2020/01/18 B 9 15
正如 Andrej Kesely 在评论中提出的那样,您正在尝试进行累积求和。 cumsum 是你想要的 numpy 函数。这应该可以解决问题。
df['Subtotal amount'] = df.amount.cumsum()
感谢 Andrej,我只是将其移至答案