Merged Excel Column Headers in Pandas

Viewed 30

I'm trying to read an excel file that has some merged column headers using pandas. The file looks as below:

enter image description here

I want the output to be as below:

enter image description here

After loading it to pandas, the output comes as below:

enter image description here

Does anyone know how I can handle this in Pandas?

Thanks

1 Answers

This is usually called multiple headers, - and pd.read_excel also pd.read_csv has options to represent it. simply use, header parameter. Later flatten the header as per example below:

df = pd.read_excel('test.xlsx', header=[0,1]) # using first and second row as headers (pandas count rows from 0).
df.columns = ['.'.join(col).strip() for col in df.columns.values] # flattening headers to a single row, - joining them using ".".

you can also test/play with to_flat_index() function, but I have not found it attractive.

df.columns = df.columns.to_flat_index()
Related