【Python】多年数据分成不同sheet

需求:

excel文件中包含多年数据,其中一列列名为"年",要保存一个新excel,将年数值不同的行保存在不同的sheet文件中,每个sheet文件第一行仍为原数据第一行,并且每个sheet名为对应的年的值。

拆分年份数据.py

python 复制代码
import pandas as pd

# Replace 'input_file.xlsx' and 'output_file.xlsx' with your actual file paths
input_file = 'input_file.xlsx'
output_file = 'output_file.xlsx'

# Read the Excel file
df = pd.read_excel(input_file)

# Print the column names
print("Column names:", df.columns)

# Update the column name based on the actual column name in your Excel file
# For example, if the column name is 'Year', replace '年' with 'Year'
column_name = '年'  # Update this to the actual column name
grouped = df.groupby(column_name)

# Create a new Excel writer
with pd.ExcelWriter(output_file, engine='xlsxwriter') as writer:
    # Iterate over groups and save each group to a separate sheet
    for group_name, group_df in grouped:
        # Create a new sheet with the group name
        group_df.to_excel(writer, sheet_name=str(group_name), index=False, header=True)
        
        # Get the worksheet and add a header row
        worksheet = writer.sheets[str(group_name)]
        worksheet.write_string(0, 0, df.columns[0])  # assuming the first column is the header

# Print a message
print(f"Data has been saved to {output_file}")
相关推荐
纤纡.3 分钟前
基于 PyTorch 手动实现 CBOW 词向量训练详解
人工智能·pytorch·python·深度学习
词元Max6 分钟前
2.5 Python 类型注解与运行时类型检查
开发语言·python
沪漂阿龙8 分钟前
深度解析Pandas数据组合:从concat到merge,打通你的数据处理任督二脉
python·数据分析·pandas
童园管理札记14 分钟前
2026实测|GPT-4.5+Agent智能体:3小时搭建企业级客服系统,附完整源码与部署教程(一)
经验分享·python·深度学习·重构·学习方法
福楠21 分钟前
现代C++ | C++14甜点特性
linux·c语言·开发语言·c++
大飞记Python22 分钟前
【2026更新】Python基础学习指南(AI版)——安装
自动化测试·python·ai编程
charlie11451419124 分钟前
嵌入式C++教程实战之Linux下的单片机编程:从零搭建 STM32 开发工具链(4)从零构建 STM32 构建系统
linux·开发语言·c++·stm32·单片机·学习·嵌入式
钰fly27 分钟前
Halcon联合编程适应图像的方法(picture)
开发语言·前端·javascript
束尘29 分钟前
Vue3一键复制图片到剪贴板
开发语言·javascript·vue.js
AI街潜水的八角33 分钟前
YOLO26手语识别项目实战1-三十五种手语实时检测系统数据集说明(含下载链接)
python·深度学习