将Pandas DataFrame写入MySQL数据库

3
我正在尝试使用以下代码将pandas数据框写入MySQL数据库。
import pandas as pd
import numpy as np
from pandas.io import sql
import MySQLdb

df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD'), [1.1, 1.7, 2.5, 2.6, 3.3, 3.8,4.0,4.2,4.3,4.5,4.6,4.7,4.7,4.8]]).T

db = MySQLdb.connect("192.168.56.101","nilani","123","test")
cursor = db.cursor()

cursor.execute("DROP TABLE IF EXISTS TEST")

sql = """CREATE TABLE TEST (
         ID  INT NOT NULL,
         COL1 CHAR(20),
         COL2 CHAR(20),  
         COL3 CHAR(20))"""

cursor.execute(sql)

sql.write_frame(df, con=db, name='TEST', flavor='mysql')

db.close()

我一直在参考这个问题和其他资源。但是我遇到了以下错误,原因是什么呢?

sql.write_frame(df, con=db, name='TEST', flavor='mysql')
AttributeError: 'str' object has no attribute 'write_frame'
1个回答

7
您已经覆盖了 from pandas.io import sql 的内容,将其替换成了 sql = """...,因此 sql 现在是一个字符串,不再是包含 write_frame 函数的 pandas 模块。

编辑:您收到的 AttributeError: 'numpy.int64' object has no attribute 'replace' 错误是由于使用整数列标签(这是一个错误)。尝试将列标签设置为其他内容,例如:

df.columns = ['COL1', 'COL2', 'COL3']

好的,那么现在我该做什么? - Nilani Algiriyage
在删除表创建代码后,我尝试了以下操作...sql.write_frame(df, con=db, name='TEST', if_exists='replace', flavor='mysql'),它显示:AttributeError: 'numpy.int64'对象没有'replace'属性。 - Nilani Algiriyage
注意,'replace'选项似乎存在一个错误(请参见例如https://github.com/pydata/pandas/issues/2971)。如果没有使用`if_exists ='replace'`,它是否可以运行? - joris
回答如何做:只需将表格创建代码重命名为sql以外的其他名称,并使用cursor.execute(other_name)执行它。 - joris
没有使用replace时,会出现以下错误:ValueError: 表'NEW'已经存在。使用replace后仍然会出现上述错误。我按照你说的做了,现在问题出在这个replace上。:( - Nilani Algiriyage
我认为目前最好的选择是在MySQL中自己删除表格,如果你想要覆盖它(因为“replace”目前无法工作:https://github.com/pydata/pandas/issues/4110)。请注意,您不必事先创建表格,“write_frame”会为您完成。 - joris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接