在Python中设置数据框列表的名称

时间:2017-10-19 17:41:45

标签: python

我读了目录

中的多个文件
files = sorted(glob("df*.csv"))    
dfList = [pd.read_csv(f) for f in files]
print(files)

['df.csv', 'df08.csv', 'df1.csv', 'df2csv.csv', 'df3.csv', 'dfcsv.csv', 'dfcsv_withsep.csv']

我想为dfList中的每个数据集设置旧名称,所以我尝试循环

names = ['df.csv', 'df08.csv', 'df1.csv', 'df2csv.csv', 'df3.csv', 'dfcsv.csv', 'dfcsv_withsep.csv']
list_names = [i.split(".")[0] for i in names]
print(list_names)

['df', 'df08', 'df1', 'df2csv', 'df3', 'dfcsv', 'dfcsv_withsep']

for i in list_names:
    for j in dfList:
        i = pd.DataFrame(j)

它不起作用,如果我手动操作,它可以工作。

df = dfList[0]
df08 = dfList[1]
df1 = dfList[2]

我做错了吗?

1 个答案:

答案 0 :(得分:0)

你的for循环中什么也没做。您只是分配对任何结果都没有影响的局部变量i。您需要将您想要的结果存储到您可以使用的内容中,例如:

names = ['df.csv', 'df08.csv', 'df1.csv', 'df2csv.csv', 'df3.csv', 'dfcsv.csv', 'dfcsv_withsep.csv']
list_names = [i.split(".")[0] for i in names]
new_names = dict()
for i in list_names:
    for j in dfList:
        new_names[i]=pd.DataFrame(j)

或类似的东西。