python - 从多个文件构建数据框,其中每个文件包含列数据
问题描述
我有一个包含多个 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"]
解决方案
# 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]
推荐阅读
- javascript - 将函数映射到数组时,GAS 导致“参数与方法签名不匹配”异常
- vb.net - 在用户回答多项选择题后,如何让我的程序在 vb.net 中继续下一个问题?
- android - 当应用程序在后台运行时,Android Listener 停止运行
- crop - 如何基于掩码裁剪所有对象,Mask-RCNN
- jmeter - 如何在 JSON POST 请求中关联两个变量
- c++ - 不同概念的 C++ 不同 using 声明
- amazon-web-services - HTML 无法访问 Amazon S3 存储桶 css 和 js 文件夹
- javascript - 为什么我的对象中的属性值重复?
- python - 如何在课堂上的一个函数中使用 celery 进度条?
- javascript - 是否有用于函数调用或变量的 Javascript 事件