gpt4 book ai didi

python - 在 csv 文件中查找每个月的最高温度?

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:35 25 4
gpt4 key购买 nike

我需要一些帮助。所以我有一个 large csv file (+8785 行)。

所以,我基本上需要的是获取每个月的最高温度。例如(输出):

Month Max Temperature

January 5.3
February 6.1
March 25.5
...

我是这样写的:

temp = open("weather_2012.csv","r")
total = 0
maxt = 0.0

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

print("Maximum:",maxt)

但它只获得了整个月(总体)的一个最高温度:

Maximum: 33.0

最佳答案

这是我认为的好方法,因为它避免了将许多(如果不是大多数)值硬编码到所需的代码中(因此适用于任何年份,并使用特定于区域设置的月份名称):

from calendar import month_name
import csv
from datetime import datetime
import sys

filename = 'weather_2012.csv'
max_temps = [-sys.maxsize] * 13 # has extra [0] entry

with open(filename, 'r', newline='') as csvfile:
reader = csv.reader(csvfile); next(reader) # skip header row
for date, high_temp, *_ in reader:
month = datetime.strptime(date, '%Y-%m-%d %H:%M:%S').month
max_temps[month] = max(max_temps[month], float(high_temp))

print('Monthly Max Temperatures\n')
longest = max(len(month) for month in month_name) # length of longest month name
for month, temp in enumerate(max_temps[1:], 1):
print('{:>{width}}: {:5.1f}'.format(month_name[month], temp, width=longest))

输出:

Monthly Max Temperatures

January: 5.3
February: 6.1
March: 25.5
April: 27.8
May: 31.2
June: 33.0
July: 33.0
August: 32.8
September: 28.4
October: 21.1
November: 17.5
December: 11.9

关于python - 在 csv 文件中查找每个月的最高温度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com