整合多个pandas数据框与不可预知的列标题/订单到单个框架或列表

我已经在这个话题上search了很多,并且找不到解决这个特定问题的任何问题。 铌我对编码和python很新。

我正在阅读多个结构相似的excel源数据文件,但列标题是不可预知的,因为顺序可能会更改,某些文件列中的某些列标题会丢失,而其他文件则不会。

import pandas as pd import glob import csv import os outfile = open('./output/output.csv','w') big_df = pd.DataFrame() dataList = [] path = "./files/" #load xlsx files from directory allFiles = glob.glob(os.path.join(path, "*.xlsx")) # loop through each file, finding the right sheet for f in allFiles: try: #read sheet as dataframe and append to list df = pd.read_excel(f, index_col=None, header=0, sheetname='sheetToRead') dataList.append(df) except: [handle error] #concatenate the list into a dataframe big_df = pd.concat(dataList) #output the dataframe to csv big_df.to_csv(outfile) 

这个代码工作正常,当所有的Excel表都有相同的一组列 – 但我有大量的源文件迭代,其中很多有不可预知的列标题和列标题的sorting,例如:

文件示例1:

 col1 col2 col3 col4 apple orange banana tangerine 

文件示例2:

 col1 col3 col4 col5 green violet red azul 

文件示例3:

 col2 col4 col5 col6 cactus bonsai oak sycamore 

有很多列组合,我想要自动读取列标题,并在输出文件中同步它们,使用列标题string作为关键,所以输出具有所有的列,但只是打印空行/南,那里有没有列/数据,例如

输出文件:

 col1 col2 col3 col4 col5 col6 apple orange banana tangerine Nan Nan green Nan violet red azul Nan Nan cactus Nan bonsai oak sycamore 

最后,这里是我尝试在这些types的文件上运行代码时得到的错误:

 Traceback (most recent call last): File "\script.py", line 27, in <module> big_df = pd.concat(dataList) File "C:\Python35-32\lib\site-packages\pandas\tools\merge.py", line 845, in concat copy=copy) File "C:\Python35-32\lib\site-packages\pandas\tools\merge.py", line 878, in __init__ raise ValueError('No objects to concatenate') ValueError: No objects to concatenate 

欢迎任何build议,不一定非得使用pandas。