4

I have a dataframe that I've imported as follows.

df = pd.read_excel("./Data.xlsx", sheet_name="Customer Care", header=None)

I would like to set the first three rows as column headers but can't figure out how to do this. I gave the following a try:

df.columns = df.iloc[0:3,:]

but that doesn't seem to work.

I saw something similar in this answer. But it only applies if all sub columns are going to be named the same way, which is not necessarily the case.

Any recommendations would be appreciated.

1 Answer 1

11
df = pd.read_excel(
    "./Data.xlsx", 
    sheet_name="Customer Care", 
    header=[0,1,2]
)

This will tell pandas to read the first three rows of the excel file as multiindex column labels.

If you want to modify the rows after you load them then set them as columns

#set the first three rows as columns
df.columns=pd.MultiIndex.from_arrays(df.iloc[0:3].values)
#delete the first three rows (because they are also the columns
df=df.iloc[3:]
Sign up to request clarification or add additional context in comments.

3 Comments

And a great name you have chosen.
thanks for the response. Is there any way to set the header after I import the excel sheet? I should have specified this in the question but I need to modify those rows before they're ready to be headers.
@neanderslob I've edited the answer to address this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.