【问题标题】:Repeat same method on multiple objects in python对python中的多个对象重复相同的方法
【发布时间】: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 中。你确定你有联系吗?引擎变量的值是多少?

标签: python list pandas


【解决方案1】:

问题似乎出在这里:

 name = onlyfiles[filenum][:-4] #name = 'example.txt'
 dsname = name #dsname = name = 'example.txt'
 print name
 name = pd.read_csv(path, sep = '\t') #name = DataFrame
 print '%s has been imported' % dsname
 dataframelist.append(dsname) #'example.txt' is appended

我添加了 cmets 以及每个阶段发生的情况。当您加载数据框时 - 您永远不会保存它们!您只将他们的名字保留在列表中。

【讨论】:

    猜你喜欢
    • 2012-09-23
    • 1970-01-01
    • 2022-06-24
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    相关资源
    最近更新 更多