PV8
PV8

Reputation: 6260

Use part of first row and part of second row as column headers in python pandas

I have a smiliar question to this one.

But somehow the solotion is not working, my dataframe looks like:

    Unnamed: 0  Unnamed: 1  Unnamed: 2  Unnamed: 3      Ist 1-4     Plan 1-4    HoRe 04     Plan
0   D           B           Hil           V Gesamt:     -83053      -83628    -262596     -257276
1   V           V           Vor            Perso        -896        -833    -2720         -2504

So basically I need to have for the first four columns the row number 0 as headers (D B Hil V Gesamt:) and then the last 4 columns (Ist 1-4 Plan 1-4 HoRe 04 Plan), when I run the script:

#set first row by columns names
df.iloc[0,:] = df.columns

#reset_index
df = df.reset_index()
#set columns from first row
df.columns = df.iloc[0,:]
df.columns.name= None
#remove first row
df.iloc[1:,:]

its still wrong, the outcome does not change.

My output should be:

    D   B   Hil     V Gesamt        Ist 1-4     Plan 1-4    HoRe 04     Plan
0   V    V  Vor     Perso           -896        -833       -2720         -2504

Upvotes: 2

Views: 371

Answers (1)

jezrael
jezrael

Reputation: 862671

I think you can convert first 4 values of first row to list and add to all columns names:

df.columns = df.iloc[0,:4].tolist() + df.columns[4:].tolist()
#alternative
#df.columns = np.concatenate([df.iloc[0,:4], df.columns[4:]])
df = df.iloc[1:].reset_index(drop=True)
print (df)
   D  B  Hil V Gesamt:  Ist 1-4  Plan 1-4  HoRe 04  Plan
0  V  V  Vor     Perso     -896      -833    -2720 -2504

Upvotes: 1

Related Questions