在CSV文件中查找最大值

时间:2014-02-13 23:07:37

标签: python csv python-3.x max import-from-csv

在文件“BoulderWeatherData.csv”中找到平均和最大降雨量的分配。使用此代码找到了平均值:

    rain = open("BoulderWeatherData.csv", "r")
    data = rain.readline()
    print(rain)
    data = rain.readlines()
    total = 0
    linecounter = 0
    for rain in data:
        linecounter = linecounter + 1
        print("The number of lines is", linecounter)

    for line in data:
        r = line.split(",")
        total = total + float(r[4])
    print(total)


    average = float(total / linecounter)
    print("The average rainfall is ", "%.2f" % average)

然而,使用相同的过程似乎无法找到最大值。尝试使用 max ,但必须获得的答案是浮点数,不能通过 max 迭代。

任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:2)

这是我处理此问题的首选方式。

#!/usr/bin/env python3

rain = open("BoulderWeatherData.csv","r")

average = 0.0
total = 0
maxt = 0.0

for line in rain:
    try:
        p = float(line.split(",")[4])
        average += p
        total += 1
        maxt = max(maxt,p)
    except:
        pass

average = average / float(total)

print("Average:",average)
print("Maximum:",maxt)

这将输出:

Average: 0.05465272591486193
Maximum: 1.98

答案 1 :(得分:1)

import csv

INPUT  = "BoulderWeatherData.csv"
PRECIP = 4   # 5th column

with open(INPUT, "rU") as inf:
    incsv  = csv.reader(inf)
    header = next(incsv, None)    # skip header row
    precip = [float(row[PRECIP]) for row in incsv]

avg_precip = sum(precip, 0.) / (1 and len(precip))  # prevent div-by-0
max_precip = max(precip)

print(
    "Avg precip: {:0.3f} in/day, max precip: {:0.3f} in/day"
    .format(avg_precip, max_precip)
)

返回

Avg precip: 0.055 in/day, max precip: 1.980 in/day

答案 2 :(得分:0)

max=0 
for line in data:
      r = line.split(",")
      if float(r[4]) > max:
           max=float(r[4])
print(max)

类似的东西

答案 3 :(得分:0)

您已经在循环迭代中累积了total

要跟踪maxvalue,它基本上是相同的,除了不是添加你max

total = 0
maxvalue = 0

for line in data:
    r = line.split(",")
    value = float(r[4])
    total = total + value
    maxvalue = max(maxvalue, value)

print(total)
print(maxvalue)

或者,如果您不想使用max功能:

for line in data:
    r = line.split(",")
    value = float(r[4])
    total = total + value
    if value > maxvalue:
        maxvalue = value

答案 4 :(得分:-1)

此代码将尝试查找存储在.csv中第5个位置的浮点数的最大值和平均值。

rainval = []

初始化我们将存储值的空数组。

with open ("BoulderWeatherData.csv", "r") as rain:

打开.csv文件并将其命名为“rain”。

    for lines in rain:

这将读取雨中的每一行,直到文件结束。

        rainval += [float(lines.strip().split(",")[4])]

我们追加在该行的第五个位置(第四个索引)中找到的浮点值。

我们对位于.csv文件中的每一行重复上述内容。

print (sorted(rainval)[len(rainval)])

这会对rainval数组中的值进行排序,然后获取最后一个(最大)值并打印它。这是最大值,并且优于max,因为它可以处理浮点数而不仅仅是整数。

print (sum(rainval)/len(rainval))

打印平均降雨量。


或者,如果我们不想使用数组:

maxrain = -float("inf")
total, count = 0, 0
with open ("test.txt", "r") as rain:
    for lines in rain:
        temp = float(lines.strip().split(",")[4])
        if maxrain < temp:
            maxrain = temp
        total += temp
        count += 1

print (maxrain)
print (total/count)