[英]use a loop to read and save different files under different dataframes
I have 4 different excel files.我有 4 个不同的 excel 文件。 I would like to open and save each of them under a variable name of the same name as the excel file with a loop (in python).
我想用一个循环(在python中)打开并保存它们中的每一个,并将它们保存在一个与excel文件同名的变量名下。 So I just want to create 4 different pandas dataframes.
所以我只想创建 4 个不同的 pandas 数据帧。 The step where it keeps getting stuck is when I allocate the name of the dataframe.
它一直卡住的步骤是当我分配 dataframe 的名称时。
files = ["id_2021_05_11",
"char_2021_05_11",
"id_2021_05_25",
"char_2021_05_25"
]
for file in files:
"{}".format(file) = pd.read_excel(r'C:\Users\...\{}.xls'.format(file), index_col=0)
I've seen suggestions to create a list or dictionnary and append each of them into the list/dict.我已经看到了创建列表或字典的建议,并将 append 每个都放入列表/字典中。 But that's not what I want.
但这不是我想要的。 I just want 4 dataframes.
我只想要4个数据框。
Here is a way to do so:这是一种方法:
files = ["id_2021_05_11",
"char_2021_05_11",
"id_2021_05_25",
"char_2021_05_25"]
for file in files:
exec(file + " = pd.read_excel(r'C:\Users\...\{}.xls'.format(file), index_col=0)")
# Check dfs
print(id_2021_05_11.head())
print(char_2021_05_11.head())
print(id_2021_05_25.head())
print(char_2021_05_25.head())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.