python - 使用Python从文件夹中按顺序读取多个excel文件

标签 python excel pandas sorting concat

我有一个文件夹,其中包含几个 xls 和 xlsx 格式的 excel 文件,我正在尝试读取它们并将它们连接到一个数据框中。我面临的问题是python没有以正确的顺序读取文件夹中的文件。

我的文件夹包含以下文件:
190.xls、195.xls、198.xls、202.xlsx、220.xlsx 等

这是我的代码:

import pandas as pd
from pathlib import Path

my_path = 'my_Dataset/'

xls_files = pd.concat([pd.read_excel(f2) for f2 in Path(my_path).rglob('*.xls')], sort = False)

xlsx_files = pd.concat([pd.read_excel(f1) for f1 in Path(my_path).rglob('*.xlsx')],sort = False)

all_files = pd.concat([xls_files,xlsx_files],sort = False).reset_index(drop=True))

我得到了我想要的,但是文件没有按照它们在文件夹中的顺序连接!!!!!!
这意味着在 all_files 数据框中我首先有来自 202.xlsx 的数据,然后来自 190.xls

我怎么解决这个问题?
先感谢您!

最佳答案

尝试使用

import pandas as pd
from pathlib import Path

my_path = 'my_Dataset/'
all_files = pd.concat([pd.read_excel(f) for f in sorted(list(Path(my_path).rglob('*.xls')) + list(Path(my_path).rglob('*.xlsx')), key=lambda x: int(x.stem))],sort = False).reset_index(drop=True) 

关于python - 使用Python从文件夹中按顺序读取多个excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60373067/

相关文章:

python - Flask 无法更改主机名

excel - 绝对引用 - 在用 R1C1 表示法编写的等式中插入 '$' 的等价物

python - Pandas - 用不同的长度对每一行进行子串

python - 如果 A 列中的单元格为空,则修改 B 列中的单元格

python - 数据未使用 python mysql.connector 存储在 mysql 中

python - Pandas 中每组的重新采样聚合

python - Django - 给定时区、月份和年份,获取该时区该日期创建的所有帖子

c# - 如何使用 linq 从 Excel 中检索数据?

excel - 创建新 Excel.Application 时出现运行时错误 "Element not found"

python - 如何根据原始数据帧组合和过滤最终数据帧?