You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中计算指定区间列的求和并赋值给变量

Pandas计算指定acc区间内的amount总和

实现步骤

  1. 先导入pandas库,若还未创建目标DataFrame,可先构造示例数据:
import pandas as pd

# 构造符合要求的DataFrame
df = pd.DataFrame({
    'acc': [1010, 2000, 3000, 5000, 6000],
    'accname': ['turnover', 'salaries', 'rent', 'assets', 'liabilities'],
    'amount': [10000, -4000, -1500, 15000, -15000]
})
  1. 筛选acc列在1010到3000区间的行,计算对应amount列的总和并赋值给result:
    有两种简洁的实现方式:
  • 方式一:使用布尔索引
result = df[(df['acc'] >= 1010) & (df['acc'] <= 3000)]['amount'].sum()
  • 方式二:使用between()方法简化条件判断
result = df[df['acc'].between(1010, 3000)]['amount'].sum()

执行后result的值为4500,与预期计算结果一致。

内容的提问来源于stack exchange,提问作者Jesper Holm-Pedersen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 22:55:17