使用 pandas 计算数据框中列的总和

Swe*_*tha 4 python sum dataframe pandas output

我需要将正值之和作为数据框中一列的一个值,并将负值之和作为一个值。例如:-

date       |  amount
2021-09-02 | 98.3
2021-08-25 |  -23.4
2021-08-14 | 34.57
2021-07-30 | -87.9
Run Code Online (Sandbox Code Playgroud)

然后我需要 (98.3+34.57) 和 (-23.4-87.9) 作为输出

jez*_*ael 6

Series.clip与以下一起使用sum

pos = df['amount'].clip(lower=0).sum()
neg = df['amount'].clip(upper=0).sum()
print (pos)
132.87
print (neg)
-111.3
Run Code Online (Sandbox Code Playgroud)

或者使用DataFrame.locwithsum和过滤Series.gt来获得更大的值,~用于负值的反转掩码:

m = df["amount"].gt(0)
pos = df.loc[m, "amount"].sum()
neg = df.loc[~m, "amount"].sum()
print (pos)
132.87
print (neg)
-111.3
Run Code Online (Sandbox Code Playgroud)