ah bon
ah bon

Reputation: 10051

Fill empty cell and rename column name of the multi-index header from excel file in Python

Given a excel file with the following format:

enter image description here

Reading with: df = pd.read_excel(file, header=[0,1], index_col=[0])

Out:

         2018           2019      
name quantity price quantity price
bj         10     2        6     5
sh          7     2        3     2

I want to manipulate the multi-index headers by filling the empty cell with year and rename name as city.

How could I do that in Pandas?

enter image description here

Upvotes: 1

Views: 421

Answers (1)

jezrael
jezrael

Reputation: 863281

Use DataFrame.rename_axis:

df = df.rename_axis(columns=['year','city'])

If possible there is index name and necessary remove, set to None:

df = df.rename_axis(columns=['year','city'], index=None)

Upvotes: 1

Related Questions