我正在读取多个文件并将它们添加到列表中:
import pandas as pd
import glob
import ntpath
path = r'C:\Folder1\Folder2\Folder3\Folder3'
all_files = glob.glob(path + "/*.dat") #.dat files only
mylist = []
for filename in all_files:
name = ntpath.basename(filename) # for renaming the DF
name = name.replace('.dat','') # remove extension
try:
name = pd.read_csv(filename, sep='\t', engine='python')
mylist.append(name)
except:
print(f'File not read:{filename}')
现在,我只想在此列表中显示DF。
这是我尝试过的:
for thing in mylist:
print(thing.name)
AttributeError: 'DataFrame' object has no attribute 'name'
还有
for item in mylist:
print(item)
但这只是打印整个DF内容。
答案 0 :(得分:1)
name = pd.read_csv(filename, sep='\t', engine='python') mylist.append(name)
在这里,name
是一个数据框,而不是您的数据框的名称。
要在数据框中添加名称,请使用
df = pd.read_csv(filename, sep='\t', engine='python')
df_name="Sample name"
mylist.append({'data':df, 'name':df_name})
>>> print(thing['name'])
Sample name
答案 1 :(得分:0)
您可以为此使用字典。
写辞:
import pandas as pd
import glob
import ntpath
path = r'C:\Folder1\Folder2\Folder3\Folder3'
all_files = glob.glob(path + "/*.dat") #.dat files only
mydict = {}
for filename in all_files:
name = ntpath.basename(filename) # for renaming the DF
name = name.replace('.dat','') # remove extension
try:
mydict[name] = pd.read_csv(filename, sep='\t', engine='python')
except:
print(f'File not read:{filename}')
要再次读取df(例如filename1
):
df = mydict['filename1']
或遍历mydict
中的所有df:
for df in mydict.values():
# use df...
或:
for key in mydict:
print(key)
df = mydict[key]
# use df...