import openpyxl
from datetime import datetime
from collections import defaultdict
# 读取原始Excel文件
source_file = 'your_source_file.xlsx'
wb = openpyxl.load_workbook(source_file)
ws = wb.active
# 创建新的Excel文件并添加工作表
new_wb = openpyxl.Workbook()
new_ws = new_wb.active
new_ws.title = "Processed Data"
# 向新工作表添加标题
new_ws.append(['stame', 'time', 'MPRE'])
# 使用字典存储每个月的MPRE总和
monthly_sums = defaultdict(float)
# 遍历原始工作表的行
for row in range(2, ws.max_row + 1):
# 获取A列(站名),B列(时间)和S列(降水量)的值
stame = ws.cell(row=row, column=1).value
time_value = ws.cell(row=row, column=2).value
mpre = ws.cell(row=row, column=19).value
# 根据新的时间格式转换
date_obj = datetime.strptime(time_value, "%Y/%m/%d")
# 将日期格式化为“YYYY-MM”
time_str = datetime.strftime(date_obj, "%Y-%m")
# 计算每个月的MPRE累加值
monthly_sums[stame, time_str] += mpre
# 将计算出的月度MPRE总值添加到新的工作表中
for (stame, time_str), total_mpre in monthly_sums.items():
new_ws.append([stame, time_str, total_mpre])
# 保存新的Excel文件
new_file_name = 'processed_data.xlsx'
new_wb.save(new_file_name)