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

如何在Python导入的CSV中获取最大值的垂直索引(行位置)

获取CSV中最大值的垂直索引(行位置)

你可以通过以下几种方式修改代码,拿到最大值对应的行索引:

方法一:遍历过程中实时跟踪(效率更高)

直接在遍历CSV行的时候,记录行号并更新最大值对应的行位置,不用额外存储所有温度值:

import csv

max_temp = -float('inf')
max_row_num = -1

with open('CSV_load.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    # 如果你的CSV有表头,先跳过表头行(没有表头就删掉这行)
    next(readCSV)
    # enumerate的start=1让行号从1开始计数(对应文件里的实际行号)
    for row_num, row in enumerate(readCSV, start=1):
        current_temp = int(row[2])
        name = row[0]
        surname = row[1]
        mark = row[2]
        print(name, surname, mark)
        
        # 发现更大的值时,更新最大值和对应的行号
        if current_temp > max_temp:
            max_temp = current_temp
            max_row_num = row_num

print("\n")
print("The highest mark is:", max_temp)
print("Its row number in the CSV file:", max_row_num)

方法二:基于你现有代码修改

利用你已经存储的maxTemp列表,通过index()方法找到最大值的索引。注意如果有多个相同最大值,index()只会返回第一个出现的位置:

import csv

with open('CSV_load.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    names = []
    surnames = []
    marks = []
    maxTemp=[]
    # 有表头就跳过,没有就删除这行
    # next(readCSV)
    for row in readCSV:
        current_temp = int(row[2])
        maxTemp.append(current_temp)
        name = row[0]
        surname = row[1]
        mark = row[2]

        print(name, surname, mark)
    print("\n")
    highest_mark = max(maxTemp)
    print("The highest mark is:", highest_mark)
    # 拿到最大值在maxTemp中的索引(从0开始)
    vertical_index = maxTemp.index(highest_mark)
    # 如果有表头,文件中的实际行号是索引+2(表头占1行,数据行从第2行开始);没有表头的话就是索引+1
    print("Its row number in the CSV file:", vertical_index + 2)

补充:获取所有最大值的行位置

如果CSV中有多个相同的最大值,用列表推导式收集所有对应的索引:

highest_mark = max(maxTemp)
all_row_indices = [i for i, temp in enumerate(maxTemp) if temp == highest_mark]
print("All rows with the highest mark:", all_row_indices)

内容的提问来源于stack exchange,提问作者Brandon Miller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:20:34