【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}")
相关推荐
li99yo8 小时前
3DGS的复现
图像处理·pytorch·经验分享·python·3d·conda·pip
潜创微科技--高清音视频芯片方案开发12 小时前
2026年C转DP芯片方案深度分析:从适配场景到成本性能的优选指南
c语言·开发语言
Dontla12 小时前
用pip install -e .开发Python包时,Python项目目录结构(项目结构)(可编辑安装editable install)
python·pip
Thomas.Sir12 小时前
第三章:Python3 之 字符串
开发语言·python·字符串·string
刘景贤12 小时前
C/C++开发环境
开发语言·c++
威联通网络存储14 小时前
告别掉帧与素材损毁:威联通 QuTS hero 如何重塑影视后期协同工作流
前端·网络·人工智能·python
Dxy123931021614 小时前
Python 根据列表中某字段排序:从基础到进阶
开发语言·windows·python
competes14 小时前
学生需求 交易累计积分,积分兑换奖品
java·大数据·开发语言·人工智能·java-ee
splage14 小时前
Java进阶——IO 流
java·开发语言·python