【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}")
相关推荐
Cyber4K42 分钟前
【Python专项】进阶语法-系统资源监控与数据采集(1)
开发语言·python·php
Le_ee1 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php
苍煜2 小时前
Java开发IO零基础吃透:BIO、NIO、同步异步、阻塞非阻塞
java·python·nio
yong99902 小时前
MATLAB读取高光谱图像
开发语言·matlab
2zcode2 小时前
基于MATLAB的肝病风险评估与分期分析系统设计与实现
开发语言·matlab
小小de风呀2 小时前
de风——【从零开始学C++】(五):内存管理
开发语言·c++
ooseabiscuit2 小时前
Laravel6.x核心优化与特性全解析
android·开发语言·javascript
折哥的程序人生 · 物流技术专研2 小时前
Java面试85题图解版(一):基础核心篇
java·开发语言·后端·面试
AllData公司负责人3 小时前
通过Postgresql同步到Doris,全视角演示AllData数据中台核心功能效果,涵盖:数据入湖仓,数据同步,数据处理,数据服务,BI可视化驾驶舱
java·大数据·数据库·数据仓库·人工智能·python·postgresql
Hello.Reader3 小时前
算法基础(十)——分治思想把大问题拆成小问题
java·开发语言·算法