python-如何使用glob.glob创建具有很多数据帧的字典

问题描述 投票:0回答:1

我使用以下代码创建了一个包含一堆数据帧的字典

files = ('auction_aggregated_curves_germany_austria_20100101.csv', 'auction_aggregated_curves_germany_austria_20100102.csv', 'auction_aggregated_curves_germany_austria_20100103.csv', 'auction_aggregated_curves_germany_austria_20100104.csv', 'auction_aggregated_curves_germany_austria_20100105.csv')

dfs = ('df1', 'df2', 'df3', 'df4', 'df5')

list_of_dfs = {}
for df, file in zip(dfs, files):
       list_of_dfs[df] = pd.read_csv(file, skiprows=1)

[但是我想知道是否有一种更简单的方法可以使用glob.iglob来自动调用一堆cvs文件,该文件的最后一个数字不同-该数字表示年,月和日的日期-。我有365个以上的文件,如果有人可以帮助我避免编写所有文件名,这将非常有帮助。

提前感谢。

python loops dataframe dictionary glob
1个回答
0
投票

您可以使用the pathlib module。它包括pathlib方法。

glob

将此代码与示例数据一起使用,from pathlib import Path dataframes = {} csv_root = Path(".") for csv_path in csv_root.glob("*.csv"): key = csv_path.stem # the filename without the ".csv" extension dataframes[key] = pd.read_csv(csv_path) 字典看起来像这样:

dataframes
© www.soinside.com 2019 - 2024. All rights reserved.