简体   繁体   English

在 Pandas 中合并 Excel 列标题

[英]Merged Excel Column Headers in Pandas

I'm trying to read an excel file that has some merged column headers using pandas.我正在尝试使用 pandas 读取具有一些合并列标题的 excel 文件。 The file looks as below:该文件如下所示:

在此处输入图像描述

I want the output to be as below:我希望 output 如下:

在此处输入图像描述

After loading it to pandas, the output comes as below:加载到pandas后,output如下:

在此处输入图像描述

Does anyone know how I can handle this in Pandas?有谁知道我如何在 Pandas 中处理这个问题?

Thanks谢谢

This is usually called multiple headers, - and pd.read_excel also pd.read_csv has options to represent it.这通常称为多个标题, - 并且pd.read_excelpd.read_csv具有表示它的选项。 simply use, header parameter.只需使用, header参数。 Later flatten the header as per example below:稍后将 header 展平,如下例所示:

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.您也可以使用to_flat_index() function 进行测试/玩,但我觉得它没有吸引力。

df.columns = df.columns.to_flat_index()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM