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

如何在for循环中选取同行不同列值,实现CSV特定年份数值求和

解决CSV特定年份数值求和问题

前提说明

假设你已用pandas读取CSV文件:

import pandas as pd
df = pd.read_csv('你的文件路径.csv')

方法1:修正你写的循环逻辑

你原代码的问题是只遍历了年份列,无法对应到同一行的value值。可以用zip同时配对年份和数值进行遍历:

total_value = 0
for year, val in zip(df['years'], df['value']):
    if year == 2000:
        total_value += val
print(total_value)  # 输出8

方法2:更高效的pandas.loc写法(解决你之前.loc无效的问题)

你之前用.loc没效果大概率是写法有误,正确的用法是先筛选出年份为2000的行,再指定value列,最后调用sum()求和:

total_value = df.loc[df['years'] == 2000, 'value'].sum()
print(total_value)  # 输出8

额外简化写法

还可以直接用布尔索引结合sum,更简洁:

total_value = df[df['years'] == 2000]['value'].sum()

内容的提问来源于stack exchange,提问作者Isaac Mantelli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:22:54