【问题标题】:Construct dataframe from multiple files where each file contains column data从多个文件构造数据框,其中每个文件包含列数据
【发布时间】:2021-04-28 03:46:01
【问题描述】:

我有一个包含多个 excel 文件的文件夹

column B.xlsx
column A.xlsx
column C.xlsx
...

**这些不是实际的文件名。实际的文件名比这个更具体

每个 excel 文件都包含我要创建的较大数据框中的单个列的数据。文件格式如下

A.xlsx 栏:

Date | ID | Mass | Units
1/21    A   5.10     g
2/21    B   5.12     g
3/21    C   5.11     g

B.xlsx 栏:

Date | ID | Mass | Units
1/21    A   6.10     g
2/21    B   6.12     g
3/21    C   6.11     g

我想创建的大型数据框如下所示:

ID | Column A | Column B | Column C|....
A     5.10        6.10
B     5.12        6.12    
C     5.11        6.11     

将数据分配到正确的列很重要,但关于数据对应于哪一列的唯一指示是在文件名中。

我编写了这段代码来完成这项工作,但必须有更好的方法

files=glob.glob(r"C:\my\directory/*.xlsx")

bigDF=pd.DataFrame(columns=["ID","A","B","C"])
temp=pd.read_excel(files[0])
bigDF["ID"]=temp["ID"]
for f in files:
    temp=pd.read_excel(f)
    if "A" in f:
        bigDF["A"]=temp["Mass"]
    elif "B" in f: 
        bigDF["B"]=temp["Mass"]
    elif "C" in f:
       bigDF["C"]=temp["Mass"]

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:
    # get your files
    files = glob.glob('*.xlsx')
    # read your files set the index and locate the mass column
    # use list comprehension to iterate through your dfs and concatenate them together
    df = pd.concat([pd.read_excel(file).set_index('ID')['Mass'].rename(file.split('.')[0]) for file in files], axis=1)
    

    上面的列表理解本质上是在做:

    # iterate through your files
    for file in files:
        # read each file into memory, set the index, select the Mass column,
        # then rename the column to the file name
        pd.read_excel(file).set_index('ID')['Mass'].rename(file.split('.'))[0]
    

    【讨论】:

    • 仅供参考 - 这假设每个 id 有一个日期,并且每个文件中的日期相同。如果不是这种情况,那么您还需要将日期添加到索引中。 set_index(['ID', 'Date'])
    【解决方案2】:

    使用合并和减少 - 想法是获取所有数据帧的子集,然后合并 ID 列上的所有 df。

    from functools import reduce
    use_cols =  ['ID', 'Mass']
    data_frames =[df1,df2,df3,df4]
    data_frames = [df[use_cols] for df in data_frames]
    final_df = reduce(lambda left,right,: pd.merge(left,right,on=['ID'],
                                                how='outer'), data_frames)
    
    

    直接加载data_frame列表中的数据帧使用(在Path构造函数中提供所需的路径Path('.')表示当前目录)-

    from pathlib import Path
    data_frames = [pd.read_excel(xlsx_file,use_cols=['ID', 'Mass']) for xlsx_file in Path('.').glob('**/*.xlsx')] #you can convert this list comprehension to generator if required. 
    

    最后,要重命名列,您可以使用 -

    new_cols  = [f'Column {i}' for i in range(len(final_df.columns.values[1:]))]
    new_cols.insert(0,'ID')
    final_df.columns = new_cols
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      • 2017-02-05
      • 2020-10-15
      • 1970-01-01
      • 2017-02-17
      相关资源
      最近更新 更多