You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整Python Pandas DataFrame:列标题下移一行并重命名合并表头

Reshaping Pandas DataFrame to Match Your Desired Excel Style

Hey there! I get it—trying to reshape a DataFrame to match a specific Excel layout can feel tricky when the usual methods don’t click right away. Let’s break this down with common scenarios and concrete code examples, since you didn’t share the exact input/output table structures yet.

Common Reshaping Scenarios & Solutions

Most Excel-style DataFrame transformations fall into two categories: wide-to-long (unpivoting columns into rows) or long-to-wide (pivoting rows into columns). Here’s how to handle both:

1. Wide Table → Long Table (Unpivot)

Suppose your input Excel table looks like this (wide format with subject columns):

姓名语文数学英语
张三908592
李四889587

And you want to convert it to this long-format output:

姓名科目分数
张三语文90
张三数学85
张三英语92
李四语文88
李四数学95
李四英语87

Use Pandas’ melt() function to unpivot:

import pandas as pd

# Load your Excel file into a DataFrame
df = pd.read_excel("your_input_file.xlsx")

# Reshape with melt: keep '姓名' as the identifier column, turn other columns into rows
output_df = df.melt(
    id_vars=["姓名"],  # Columns to keep as identifiers
    var_name="科目",   # Name for the new column holding original column names
    value_name="分数"  # Name for the new column holding the values
)

# Save the result back to Excel
output_df.to_excel("your_output_file.xlsx", index=False)

2. Long Table → Wide Table (Pivot)

If you’re going the opposite direction (long to wide), use pivot():

# Starting with the long-format DataFrame
df = pd.read_excel("your_input_file.xlsx")

# Pivot to wide format
output_df = df.pivot(
    index="姓名",    # Rows to keep as the index
    columns="科目",  # Columns to turn into new wide columns
    values="分数"    # Values to fill the new columns
).reset_index()

# Remove the extra column name index for cleaner Excel output
output_df.columns.name = None

# Save to Excel
output_df.to_excel("your_output_file.xlsx", index=False)

Need a More Tailored Solution?

If your table has more complex structures—like multi-level headers, merged cells, or columns that need splitting/merging—share a small example of your input table and desired output table (with column names and sample data). That way, I can give you code that fits your exact use case!

内容的提问来源于stack exchange,提问作者PSarkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:34:10