使用文件名作为数据框中的列标题

我有多个 excel 文件,我需要将所有这些文件中的一列整理到一个数据框中。我使用了以下代码:


my_excel_files = glob.glob(r"C:\Users\......\Documents\*.xlsx")


total_dataframe = pd.DataFrame() 


for file in my_excel_files:

    df = pd.read_excel(file, header = 1) 

    new_df = df['Comments']

    total_dataframe = pd.concat([total_dataframe, new_df], axis=1)

此代码从我所有的 excel 文件中获取所有“评论”列,并将它们附加到 total_dataframe 中。问题是该数据框中的列都是“评论”,所以我无法区分每一列的来源。


有没有办法使用每个 excel 的完整文件名作为列标题,这样我就知道每个列来自哪个 excel


智慧大石
浏览 138回答 1
1回答

喵喔喔

您可以使用或列表理解创建系列列表append,然后keys在中使用参数concat:import glob, osmy_excel_files = glob.glob(r"C:\Users\......\Documents\*.xlsx")names = [os.path.basename(f).split('.')[0] for f in my_excel_files]output = []for file in my_excel_files:    df = pd.read_excel(file, header = 1)     new_df = df['Comments']    output.append(new_df)final = pd.concat(output, axis=1, keys=names)或者:import glob, osmy_excel_files = glob.glob(r"C:\Users\......\Documents\*.xlsx")names = [os.path.basename(f).split('.')[0] for f in my_excel_files]output = [pd.read_excel(file, header = 1)['Comments']  for file in my_excel_files]final = pd.concat(output, axis=1, keys=names)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python