【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}")
相关推荐
叫我:松哥10 分钟前
基于Flask框架开发的智能旅游推荐平台,采用复合推荐算法,支持管理员、导游、普通用户三种角色
python·自然语言处理·flask·旅游·数据可视化·推荐算法·关联规则
CSDN_RTKLIB17 分钟前
inline内联函数基础知识
开发语言·c++
No0d1es18 分钟前
2025年12月 GESP CCF编程能力等级认证Python四级真题
开发语言·python·青少年编程·等级考试·gesp·ccf
love530love19 分钟前
EPGF 新手教程 13在 PyCharm(中文版 GUI)中创建 Hatch 项目环境,并把 Hatch 做成“项目自包含”(工具本地化为必做环节)
开发语言·ide·人工智能·windows·python·pycharm·hatch
Ralph_Y25 分钟前
C++异常对象
开发语言·c++
baiduopenmap27 分钟前
【智图译站】GENREGION——高准确度、高可扩展的城市区域自动划分方法
开发语言·百度地图
蚰蜒螟27 分钟前
Redis网络层深度解析:数据如何写回客户端
java·开发语言·bootstrap
效率客栈老秦33 分钟前
Python Trae提示词开发实战(2):2026 最新 10个自动化批处理场景 + 完整代码
人工智能·python·ai·prompt·trae
IT 行者38 分钟前
告别硬编码!Spring Boot 优雅实现 Controller 路径前缀统一管理
数据库·spring boot·python
No0d1es42 分钟前
2025年12月 GESP CCF编程能力等级认证Python五级真题
开发语言·python·青少年编程·等级考试·gesp·ccf