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

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:

DBHilV GesamtIst 1-4Plan 1-4HoRe 04Plan
VVVor 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:42:45