从输入Excel文件中读取数据每个日期对应一个数据按日期对数据排序计算数据的平均值填充到缺失数据的日期并将数据写入输出Excel文件
以下是Python代码示例,使用openpyxl库读写Excel文件:
import openpyxl
from datetime import datetime
# 输入文件路径和输出文件路径
input_file_path = "input.xlsx"
output_file_path = "output.xlsx"
# 打开输入Excel文件和输出Excel文件
input_wb = openpyxl.load_workbook(input_file_path)
output_wb = openpyxl.Workbook()
# 获取输入Excel文件中的工作表
input_ws = input_wb.active
# 创建输出Excel文件中的工作表
output_ws = output_wb.active
output_ws.title = "Data"
# 创建一个字典,用于存储每个日期对应的数据
data_dict = {}
# 遍历输入Excel文件中的每个单元格
for row in input_ws.iter_rows():
date_cell = row[0]
data_cell = row[1]
if date_cell.value is None or data_cell.value is None:
continue
if type(date_cell.value) is not datetime:
continue
date_str = date_cell.value.strftime("%Y-%m-%d")
data = data_cell.value
data_dict[date_str] = data
# 按日期排序
sorted_data = sorted(data_dict.items())
# 计算平均值
total_data = sum([data for date, data in sorted_data])
average_data = total_data / len(sorted_data)
# 遍历日期范围,填充缺失数据
start_date = sorted_data[0][0]
end_date = sorted_data[-1][0]
current_date = start_date
index = 0
while current_date <= end_date:
if index < len(sorted_data) and sorted_data[index][0] == current_date:
data = sorted_data[index][1]
index += 1
else:
data = average_data
output_ws.append([current_date, data])
current_date = (datetime.strptime(current_date, "%Y-%m-%d") + timedelta(days=1)).strftime("%Y-%m-%d")
# 保存输出Excel文件
output_wb.save(output_file_path)
``
原文地址: http://www.cveoy.top/t/topic/hh9i 著作权归作者所有。请勿转载和采集!