我在目录“ G:\ files”下有五个文件,分别是a.csv,b.csv,c.csv,d.csv和e.csv,我想为所有文件创建不同的datafrme。 / p>
for i, j in enumerate(os.listdir(r'G:\files')):
df_name = 'df' + str(i)
df_name = pd.read_csv(j)
在for循环中没有出现任何错误,但是当我尝试打印获取NameError的数据帧时。请帮助
答案 0 :(得分:2)
更好的是创建DataFrame
个字典:
d = {'df' + str(i): pd.read_csv(j) for i, j in enumerate(os.listdir(r'G:\files'))}
import glob
#get files *.csv, thank you anki_91
d = {'df' + str(i): pd.read_csv(j) for i, j in enumerate(glob.glob('G:/files/*.csv'))}
或者:
d = {}
for i, j in enumerate(os.listdir(r'G:\files')):
d['df' + str(i)] = pd.read_csv(j)
对于每个DataFrame,请按key
s来选择字典:
print (d['df0'])
print (d['df1'])
您可能需要什么,但recommended却没有:
for i, j in enumerate(os.listdir(r'G:\files')):
globals()['df' + str(i)] = pd.read_csv(j)
答案 1 :(得分:0)
从answer开始......不用枚举,而是将每个csv文件和唯一的变量名保存到字典中。
import os
import pandas as pd
a = {}
k = 0
for file in os.listdir(r'G:\files'):
df_name = 'df' + str(k)
df_data = pd.read_csv(file)
a[df_name] = df_data
k += 1
print(type(a['df1']))
输出:
<class 'pandas.core.frame.DataFrame'>