我想对此Dataframe(命名为:loandata)进行分类,并将每个子数据帧导入许多csv文件。第一步,我尝试转换其中一个结果,但遗憾的是失败并得到了这个错误:
import pandas as pd
import csv
import os
#readfile
loandata=pd.DataFrame(pd.read_table('/Users/lixuefei/Desktop/Sample Dataset/test.txt',header = None,index_col=2))
#classify
volume_type=list(set(loandata[3]))
system_type=list(set(loandata[4]))
area_name=list(set(loandata[5]))
df=pd.DataFrame(loandata[(loandata[3]==volume_type[0])& (loandata[4]==system_type[0])&(loandata[5]==area_name[0])])
#set the file path
path='/Users/lixuefei/Desktop/Sample Dataset'
filename=volume_type[0]+system_type[0]+area_name[0]
filetype=csv
if not df.empty:
df.to_csv(os.path.join(path,filename+filetype),header=None)
else:
print("Empty")
这是错误:
/Users/lixuefei/anaconda/bin/python3.5/Users/lixuefei/PycharmProjects/project/project.11.09.py
Traceback (most recent call last):
File "/Users/lixuefei/PycharmProjects/project/project.11.09.py", line 25, in <module>
df.to_csv(os.path.join(path,filename+filetype),header=None)
TypeError: Can't convert 'module' object to str implicitly
答案 0 :(得分:1)
a)空白是你的朋友。
b)filename
是一个字符串,filetype
是csv模块。
我认为你的意思是:
filetype = "csv"
然后是下面之一:
os.path.join(path, filename + "." + filetype)
或更好:
os.path.join(path, "%s.%s" % (filename, filetype))
或“正确的”Python 3方式:
os.path.join(path, "{}.{}".format(filename, filetype))