【问题标题】:pandas to_sql only writing first row to dbpandas to_sql 只将第一行写入数据库
【发布时间】:2018-07-28 00:17:51
【问题描述】:

我正在使用以下代码将制表符分隔文件读入 postgres 数据库

enginestring = cfg.dbuser+":"+cfg.dbpwd+"@"+server.local_bind_host+":"+str(server.local_bind_port)+"/"+cfg.dbname
engine = create_engine('postgresql://' + enginestring)

rows = []
for line in smart_open.smart_open(key):
    ln = str(line.decode('utf-8'))
    fields = ln.split('\t')
    rows.append(fields)

df = pd.DataFrame(rows, columns=cfg.df_colheaders)
print(df.head)
df.to_sql(name=table_name, con=engine, if_exists='append')

对 print 的调用返回我期望的数据帧(即 [798624 行 x 133 列])并且对 to_sql 的调用没有失败,但在数据库中我只看到一行具有正确列的数据.. .(如果之前创建过表,结果相同)

【问题讨论】:

  • 我认为这不是连接问题,因为此循环创建了多个表而无需重新连接。会不会是数据问题?
  • 很奇怪。 1. df.head() 返回有意义的东西,对吗? 2. 在较小的数据集上测试代码时会发生什么,例如df = df.head() 然后df.to_sql(name=table_name, con=engine, if_exists='append')
  • 请在df.to_sql() 中添加, index=False) 看看是否起作用。

标签: python pandas pandas-to-sql


【解决方案1】:

好的,这是更新:

  • 我通过剥离 EOL 字符解决了单行问题(可以在最后插入的字段末尾看到 ¶)
  • 然后我只是得到空表,所以我向 to_sql 添加了 chunksize 参数 - 不知道为什么它没有失败,而不是只是继续,但现在一切正常

【讨论】:

    猜你喜欢
    • 2018-05-12
    • 2015-08-18
    • 2020-12-01
    • 2017-08-01
    • 1970-01-01
    • 2020-10-25
    • 2017-05-19
    • 2018-05-04
    • 2019-02-10
    相关资源
    最近更新 更多