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

如何在Pandas中将两行合并为每列的单个表头单元格

Merge Two Rows into a Single Header in Pandas

Got it, let's fix this header issue in Pandas. Here's a straightforward way to combine those two rows into a single header and get your DataFrame looking exactly how you want:

Step-by-Step Solution

  1. Create combined header names: Take the values from row 0 and row 1 for each column, join them with a space (or any separator you prefer) to form the new column headers.
  2. Update the DataFrame's columns: Assign these combined names as the new column labels.
  3. Clean up the data: Drop the first two rows (since they were the old split headers) and reset the index to start from 0 again.

Full Code Example

Let's use your sample data to demonstrate:

import pandas as pd

# Your original DataFrame
data = {
    "列1": ["A", "header", "First row", "后续数据行1", "后续数据行2"],
    "列2": ["Another", "header", "Second row", "后续数据行3", "后续数据行4"]
}
df = pd.DataFrame(data)

# Step 1: Combine rows 0 and 1 to make new headers
new_headers = [f"{df.iloc[0][col]} {df.iloc[1][col]}".strip() for col in df.columns]

# Step 2: Assign new headers to the DataFrame
df.columns = new_headers

# Step 3: Drop the old header rows and reset index
df = df.drop([0, 1]).reset_index(drop=True)

# Check the result
print(df)

Output

This will give you the desired format:

行索引A headerAnother header
0First rowSecond row
1后续数据行1后续数据行3
2后续数据行2后续数据行4

Quick Notes

  • If you prefer a different separator (like an underscore instead of a space), just replace the space in the string format with your preferred character.
  • If one of the header rows has missing values, use str.cat to handle gaps cleanly: df.iloc[0].str.cat(df.iloc[1], sep=' ', na_rep='')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 16:54:07