首页 > 解决方案 > 从多个文件构建数据框,其中每个文件包含列数据

问题描述

我有一个包含多个 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"]

标签: pythonpython-3.xpandas

解决方案


# 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]

推荐阅读