如何在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
- 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.
- Update the DataFrame's columns: Assign these combined names as the new column labels.
- 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 header | Another header |
|---|---|---|
| 0 | First row | Second 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.catto handle gaps cleanly:df.iloc[0].str.cat(df.iloc[1], sep=' ', na_rep='')
内容的提问来源于stack exchange,提问作者Taiko
相关产品推荐
相关产品推荐

