【发布时间】:2023-03-15 12:52:02
【问题描述】:
我有一个数据文件,其中包含某种特定格式的数据,并且在处理时需要忽略一些额外的行。我需要处理数据并基于相同的值计算值。
样本数据:
Average monthly temperatures in Dubuque, Iowa,
January 1964 through december 1975, n=144
24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0
16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1
10.4 21.6 37.4 44.7 53.2 68.0 73.7 68.2 60.7 50.2 37.2 24.6
21.5 14.7 35.0 48.3 54.0 68.2 69.6 65.7 60.8 49.1 33.2 26.0
19.1 20.6 40.2 50.0 55.3 67.7 70.7 70.3 60.6 50.7 35.8 20.7
14.0 24.1 29.4 46.6 58.6 62.2 72.1 71.7 61.9 47.6 34.2 20.4
8.4 19.0 31.4 48.7 61.6 68.1 72.2 70.6 62.5 52.7 36.7 23.8
11.2 20.0 29.6 47.7 55.8 73.2 68.0 67.1 64.9 57.1 37.6 27.7
13.4 17.2 30.8 43.7 62.3 66.4 70.2 71.6 62.1 46.0 32.7 17.3
22.5 25.7 42.3 45.2 55.5 68.9 72.3 72.3 62.5 55.6 38.0 20.4
17.6 20.5 34.2 49.2 54.8 63.8 74.0 67.1 57.7 50.8 36.8 25.5
20.4 19.6 24.6 41.3 61.8 68.5 72.0 71.1 57.3 52.5 40.6 26.2
示例文件来源:http://robjhyndman.com/tsdldata/data/cryer2.dat
注意:这里,行代表年份,列代表月份。
我正在尝试编写一个函数,它从给定的 url 返回任何月份的平均温度。
我试过如下:
def avg_temp_march(f):
march_temps = []
# read each line of the file and store the values
# as floats in a list
for line in f:
line = str(line, 'ascii') # now line is a string
temps = line.split()
# check that it is not empty.
if temps != []:
march_temps.append(float(temps[2]))
# calculate the average and return it
return sum(march_temps) / len(march_temps)
avg_temp_march("data5.txt")
但我收到错误line = str(line, 'ascii')
TypeError: decoding str is not supported
【问题讨论】:
-
请提供MCVE
-
删除
line = str(line, 'ascii') # now line is a string这一行 -
str接受一个参数,你给它两个。 -
当我删除你所说的行时,我得到一个索引超出范围错误我似乎无法到达月份:march_temps.append(float(temps[2])) IndexError: list索引超出范围
-
我的意思是
line已经是一个字符串了。但请务必阅读我的第一条评论
标签: python average temperature