简体   繁体   English

将Pandas DataFrame写入MySQL数据库

[英]Write Pandas DataFrame in to MySQL database

I'm trying to write a pandas dataframe to MySQL database with following code. 我正在尝试使用以下代码将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()

I have been referring this question and the other resources. 我一直在提到这个问题和其他资源。 Any way I get following error. 我有任何方式得到以下错误。 What will be the reason? 会是什么原因?

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

You have overwritten the from pandas.io import sql with sql = """... , so sql is now a string and no longer a pandas module which holds the write_frame function. 你用sql = """...覆盖了from pandas.io import sql ,所以sql现在是一个字符串,不再是一个保存write_frame函数的pandas模块。


EDIT: the AttributeError: 'numpy.int64' object has no attribute 'replace' error you get is due to the fact that you use integer column labels (this is a bug). 编辑: AttributeError: 'numpy.int64' object has no attribute 'replace'错误你得到的是由于你使用整数列标签(这是一个错误)。 Try setting the columns labels to something else, eg: 尝试将列标签设置为其他内容,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM