如何将变量保存为for循环中的不同文件?



我有一个列表中的csv文件路径名列表,我试图将它们保存为数据框架。我该怎么做呢?

import pandas as pd
import os
import glob
# use glob to get all the csv files
# in the folder
path = "/Users/azmath/Library/CloudStorage/OneDrive-Personal/Projects/LESA/2022 HY/All"
csv_files = glob.glob(os.path.join(path, "*.xlsx"))

# loop over the list of csv files
for f in csv_files:

# read the csv file
df = pd.read_excel(f)  
display(df)
print()

问题是它只打印。但我不知道怎么存钱。我想保存所有的数据帧作为变量,最好作为他们的文件名。

我想你的意思是在变量中存储数据帧。我会使用字典,而不是单独的变量。

import os

data = {}
for f in csv_files:
name = os.path.basename(f)
# read the csv file
data[name] = pd.read_excel(f)  
display(data[name])
print()

现在所有的数据帧都存储在data字典中,您可以在那里迭代它们(如果需要的话,可以轻松地将它们一起处理)。它们在字典中的键是输入文件的basename (filename)。

还记得字典记住插入顺序,所以文件插入的顺序也被保留。我可能会建议在解析之前对输入文件进行排序——这样您就可以得到一个可重复的脚本和操作序列!

try this:

a = [pd.read_excel(file) for file in csv_files]

那么a将是所有数据框架的列表。如果你想要一个字典而不是列表:

a = {file: pd.read_csv(file) for file in csv_files}

最新更新