代码之家  ›  专栏  ›  技术社区  ›  DarthVader

从多个EXCEL中合并一张工作表的数据

  •  1
  • DarthVader  · 技术社区  · 8 年前

    我有以下格式的多个excel文件:

    ID | Name | Prop1 | Prop2 | User
    

    来自excel1的数据:

    ID | Name | Prop1 | Prop2 | Prop3 | User 
    1  | test |       |       |       | John
    

    来自Excel2的数据:

    ID | Name | Prop1 | Prop2 | Prop3 | User
    1  | test |   a   |   b   |       | John
    

    来自Excel3的数据:

    ID | Name | Prop1 | Prop2 | Prop3 | User
    1  | test |       |       |   c   | John
    

    我想做的是合并这些细胞。

    所需输出:

    ID | Name | Prop1 | Prop2 | Prop3 | User
    1  | test |   a   |   b   |   c   | John
    

    如果某个文件上的单元格为空,而另一个文件中有值,我想替换它。

    有什么简单的方法可以做到这一点吗?

    谢谢

    3 回复  |  直到 8 年前
        1
  •  4
  •   jezrael    8 年前

    您可以通过以下方式创建所有数据帧的列表 glob ,用于最终 df 需要 combine_first 具有 reduce :

    import glob
    from functools import reduce
    
    files = glob.glob('files/*.xlsx')
    dfs = [pd.read_excel(fp).set_index(['ID','Name','User']) for fp in files]
    
    df1 = reduce(lambda l,r: pd.DataFrame.combine_first(l,r), dfs)
    print (df1)
                 Prop1 Prop2 Prop3
    ID Name User                  
    1  test John     a     b     c
    

    编辑:如果不需要将文件与 NaN s解决方案更简单:

    import glob
    
    files = glob.glob('files/*.xlsx')
    df = pd.concat([pd.read_excel(fp) for fp in files],ignore_index=True)
    
        2
  •  1
  •   Rehan Azher    8 年前

    请尝试以下操作:

    df1 = pd.read_excel('Excel1.xlsx', sheetname='Sheet1');
    df2= pd.read_excel('Excel2.xlsx', sheetname='Sheet1');
    df3 = pd.read_excel('Excel3.xlsx', sheetname='Sheet1')
    mylist = [df1,df2,d3]
    df = pd.merge(df1, df2, on=['ID','USER'])
    df = pd.merge(df, df3, on=['ID','USER'])
    writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
    # Convert the dataframe to an XlsxWriter Excel object.
    df.to_excel(writer, sheet_name='Sheet1')
    # Close the Pandas Excel writer and output the Excel file.
    writer.save()
    

    我还没有机会测试这个,但应该可以。

        3
  •  0
  •   ASH    8 年前

    这应该是你想要的。

    import pandas as pd
    import numpy as np
    
            import glob
            glob.glob("C:/your_path_here/*.xlsx")
    
            all_data = pd.DataFrame()
            for f in glob.glob("C:/your_path_here/*.xlsx"):
                df = pd.read_excel(f)
                all_data = all_data.append(df,ignore_index=True)
                print(all_data)