从 Python 的文件夹中按顺序读取多个 excel 文件
Read multiple excel files in order from folder with Python
我有一个文件夹,其中包含多个 excel 文件,格式为 xls 和 xlsx,我正在尝试读取它们并将它们连接到一个 Dataframe 中。我面临的问题是 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 Dataframe 中,我首先有来自 202.xlsx 的数据,然后来自 190.xls
我该如何解决这个问题?
提前致谢!
更新这个
all_files = pd.concat([xls_files,xlsx_files],sort = False).reset_index(drop=True))
至此
all_files = pd.concat([xlsx_files,xls_files],sort = False).reset_index(drop=True))
尝试使用
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)
我有一个文件夹,其中包含多个 excel 文件,格式为 xls 和 xlsx,我正在尝试读取它们并将它们连接到一个 Dataframe 中。我面临的问题是 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 Dataframe 中,我首先有来自 202.xlsx 的数据,然后来自 190.xls
我该如何解决这个问题? 提前致谢!
更新这个
all_files = pd.concat([xls_files,xlsx_files],sort = False).reset_index(drop=True))
至此
all_files = pd.concat([xlsx_files,xls_files],sort = False).reset_index(drop=True))
尝试使用
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)