用python编写程序。问题如下:有两列数据,一列是时间,形式为2011⼀5⼀31 19:00,另一列是一个具体的数值

2025-05-13 14:10:39
推荐回答(2个)
回答(1):

数据先导入,通常用csv。
然后是时间格式转换用time.strptime
转换完的时间可以直接取到hour,miniute,等属性,你直接按hour做当天平均值,再做月份的平均值。(其实可以一直计算,不用分开算)

最简单的办法是1个月的数据,全放在一起,按时间排序,然后按小时平均就可以了。
如果不想麻烦就这样
sum([v for t,v in data if t.hour==2]) /len([v for t,v in data if t.hour==2])
这句话就是计算2点的数据平均值

回答(2):

import csv
from time import strptime
T_FORMAT = '%Y/%m/%d %H:%M'
def get_key(str):
t = strptime(str, T_FORMAT)
return t.tm_mon, t.tm_hour
def handle_text(in_filename, out_filename):
with open(in_filename,'r') as csvfile:
spamreader=csv.reader(csvfile, delimiter=',', quotechar='|')
table = dict()
for row in spamreader:
m, h = get_key(row[0])
if (m,h) in table:
table[(m,h)] = table[(m,h)] + float(row[1])
else:
table[(m,h)] = float(row[1])
with open(out_filename, 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for i in range(1, 13):
spamwriter.writerow([(table[(i, j)] if (i,j) in table else 0) for j in range(0, 24)])
handle_text('666.csv', '666.gen.csv')
需要先将原excel文件导出MS-DOS格式的CSV文件
把最后一行的两个文件名修改一下就能生成了