Python Pandas合并两行部分内容作为列名失败求助
Got it, let's fix this for you! The issue with your current code is that it’s trying to replace all column names with the first row’s values, but you want to keep the original headers for the last four columns. Here’s the right approach:
First, we’ll create new column names by combining the first four values from the first row (your desired headers for the left side) with the original headers from the last four columns. Then we’ll drop the now-obsolete first row and reset the index.
Here’s the code:
# Create new column names: first 4 from row 0, rest keep original headers new_columns = list(df.iloc[0, :4]) + list(df.columns[4:]) # Optional: if you want to remove the colon from "V Gesamt:", uncomment the line below # new_columns = [col.rstrip(':') for col in df.iloc[0, :4]] + list(df.columns[4:]) # Update the DataFrame's column names df.columns = new_columns # Drop the first row (it's now used as headers) and reset the index df = df.iloc[1:].reset_index(drop=True)
Let’s break this down:
df.iloc[0, :4]grabs the first four values from the first row (D,B,Hil,V Gesamt:) to use as the new left-side headers.df.columns[4:]preserves the original headers for the last four columns (Ist 1-4,Plan 1-4,HoRe 04,Plan).- We combine these two lists to get our full set of column names.
- Finally, we remove the first row (since it’s no longer data) and reset the index to start at 0, which gives you exactly the output you want.
Testing this with your sample data will result in the structure you requested:
| D | B | Hil | V Gesamt | Ist 1-4 | Plan 1-4 | HoRe 04 | Plan |
|---|---|---|---|---|---|---|---|
| V | V | Vor Perso | -896 | -833 | -2720 | -2504 | ... |
(Quick note: I noticed your sample row 1 appears to have one fewer value—make sure your original DataFrame has consistent column counts to avoid mismatch errors.)
内容的提问来源于stack exchange,提问作者PV8

