1. 首页
  2. Pandas

pandas处理excel合并单元格成标准表格

excel的table表头合并成单元格,需要处理成表格的二维表

示例表格截图:

pandas处理excel合并单元格成标准表格

pandas一般读取:

pandas处理excel合并单元格成标准表格

pandas标准化处理后的成二维表;

pandas处理excel合并单元格成标准表格

附上代码:

import pandas as pd
file_path =r'D:\code\stock_data\猪周期\生猪供给总览.xlsx'
df = pd.read_excel(file_path,sheet_name=0, header=[0,1])
df = df.reset_index()
df = df.rename(columns=lambda x: x if not 'Unnamed' in str(x) else '')
df = df.rename(columns={'index':'ColA'})
df.columns.names = (None, None)
df.columns = [''.join(col) for col in df.columns]
del df['ColA']
df.head()

参考文档:

[python – Fix DataFrame columns when reading an Excel file with a header with merged cells – Stack Overflow](https://stackoverflow.com/questions/42132663/fix-dataframe-columns-when-reading-an-excel-file-with-a-header-with-merged-cells)

发表评论

登录后才能评论