Python 向dataframe中的列标题添加文件名

Python 向dataframe中的列标题添加文件名,python,excel,pandas,dataframe,Python,Excel,Pandas,Dataframe,我有一个数据框,它是我从7个不同的excel文件中合并一列创建的。下面是我使用的代码: import pandas as pd import glob my_excel_files = glob.glob(r"C:\Users\.........\*.xlsx") total_dataframe = pd.DataFrame() for file in my_excel_files: new_df = df['Comments'] total_data

我有一个数据框,它是我从7个不同的excel文件中合并一列创建的。下面是我使用的代码:

import pandas as pd
import glob

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

total_dataframe = pd.DataFrame() 

for file in my_excel_files:
    new_df = df['Comments']
    total_dataframe = pd.concat([total_dataframe, new_df], axis=1) # Puts together all Comments columns

正如您从代码中看到的,我从每个excel抓取“Comments”列并将它们放在一个新的df中,唯一的问题是我希望能够将文件名添加到列名中,以便我知道哪个列来自哪个excel文件,所有这些列现在都被称为“Comments”。因此理想情况下,其中一个列标题应该是“Comments(first_response.xlsx)”

让我们使用
pathlib
pd.concat

使用dict理解,我们可以从pathlib对象中获取
.name
属性,当使用
concat
时,文件名将被设置为索引

from pathlib import Path


dfs = pd.concat({f.name : pd.read_excel(f) for f in Path(r'C:\Users\..').glob('*.xlsx')})
这将创建一个带有文件名的索引,如果要将其作为列放置,您可以
重置_index