【问题标题】:using filename as column headers in data frame使用文件名作为数据框中的列标题
【发布时间】:2020-08-14 17:11:39
【问题描述】:

我有多个 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

【问题讨论】:

    标签: python excel pandas dataframe


    【解决方案1】:

    您可以使用append 或列表理解创建系列列表,然后在concat 中使用keys 参数:

    import glob, os
    
    my_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, os
    
    my_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)
    

    【讨论】:

      猜你喜欢
      • 2020-02-07
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多