我正在尝试从具有每小时风速的文件中计算平均每日风速。为此,我使用for循环来识别月份和日期的组合,然后分析每个日历日的每小时风速数据。每小时数据具有正值,如果丢失,则为-999。我编写了以下代码行,该代码成功过滤了24小时内所有丢失的数据,并返回当天的平均值:
Average_WindSpeed = sum(row[1] == m and row [2] == d and float(row[4]) if float(row[4]) > -999 else 0 for row in reader)/24
我的问题是代码的else条件将只允许我输入数字。如果输入类似else: 'Missing'
的信息,则会收到 TypeError:+不支持的操作数类型:'int'和'str'消息。我知道TypeError意味着数字和字符串的某种组合是不兼容的,我只是不了解在else语句中它是如何发生的。我正在尝试设置if语句,以便如果一天中的所有24小时都是-999,则else将返回“缺少”。该代码可与我放入的else: 0
占位符一起使用,但是,我必须传递的数值是错误的。这是大型项目中相关的代码部分:
import csv
print("Month", "Day", "WindSpeed")
months = ['01']
for m in months:
if m == '01' or m =='03' or m == '05' or m == '07' or m == '08' or m == '10' or m == '12':
dates = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']
for d in dates:
# Calculate average daily windspeed from hourly data
with open('samplehourlydata.txt', 'r') as f:
reader = csv.reader(f)
next(reader)
Average_WindSpeed = sum(row[1] == m and row [2] == d and float(row[4]) if float(row[4]) > -999 else 0 for row in reader)/2
print(Average_WindSpeed)
如果有帮助,下面是一些示例数据:
yyyy,mm,dd,hour,W Speed
1941,01,01,00,-999
1941,01,01,01,-999
1941,01,01,02,-999
1941,01,01,03,-999
1941,01,01,04,-999
1941,01,01,05,-999
1941,01,01,06,-999
1941,01,01,07,-999
1941,01,01,08,-999
1941,01,01,09,-999
1941,01,01,10,-999
1941,01,01,11,-999
1941,01,01,12,-999
1941,01,01,13,-999
1941,01,01,14,-999
1941,01,01,15,-999
1941,01,01,16,-999
1941,01,01,17,-999
1941,01,01,18,-999
1941,01,01,19,-999
1941,01,01,20,-999
1941,01,01,21,-999
1941,01,01,22,-999
1941,01,01,23,-999
1941,01,02,00, 9.2
1941,01,02,01,11.5
1941,01,02,02, 9.2
1941,01,02,03,11.5
1941,01,02,04,11.5
1941,01,02,05, 8.1
1941,01,02,06, 9.2
1941,01,02,07,11.5
1941,01,02,08, 9.2
1941,01,02,09,10.4
1941,01,02,10,12.7
1941,01,02,11,13.8
1941,01,02,12,11.5
1941,01,02,13,10.4
1941,01,02,14,11.5
1941,01,02,15,11.5
1941,01,02,16,10.4
1941,01,02,17, 6.9
1941,01,02,18, 5.8
1941,01,02,19, 9.2
1941,01,02,20,10.4
1941,01,02,21,11.5
1941,01,02,22, 4.6
1941,01,02,23, 9.2
此外,我知道还有其他方法可以执行此操作,例如可能设置字典或使用numpy,但是我实际上是在试图理解这种“其他”情况。谢谢。