【发布时间】:2014-09-20 09:27:55
【问题描述】:
这是非常基本的,但我无法通过谷歌找到答案。我有一个循环,可以将大量文本文件导入 pandas 数据帧。
我已经把名字写到一个列表中。
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) and join(mypath,f).endswith('.txt') ]
dataframelist = []
for filenum in range(1,len(onlyfiles)):
path = 'path/%s' % onlyfiles[filenum]
print path
name = onlyfiles[filenum][:-4]
dsname = name
print name
name = pd.read_csv(path, sep = '\t')
print '%s has been imported' % dsname
dataframelist.append(dsname)
我现在希望在每个对象上运行 to_sql() 方法,但似乎找不到正确的语法。据我了解,对象已经实例化,但解释器认为我正在尝试操作字符串对象。
然后我获取 pandas 对象的列表
#if a dataframe exists and has a '-customer' at the end then import
custlist = []
for item in list(dataframelist):
if item.endswith('-customer'):
custlist.append(item)
并尝试循环使用该方法
for dsname in range(1,5):
ds_to_sql = custlist[dsname]
print ds_to_sql
(ds_to_sql.to_sql('%s', engine)) % ds_to_sql
我确信这是非常基本的,非常感谢您的帮助。
【问题讨论】:
-
您是如何尝试运行
to_sql方法的? -
我已将另一个代码块添加到问题中
-
那么
custlist是什么?它包含什么?ds_to_sql每次是什么 - 一个字符串,还是一个数据框对象? -
你能告诉我们python告诉你的错误吗? to_sql 方法用于将数据插入到您已经建立连接的数据库中的 table 中。你确定你有联系吗?引擎变量的值是多少?