[英]Write Pandas DataFrame in to MySQL database
我正在嘗試使用以下代碼將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'
你用sql = """...
覆蓋了from pandas.io import sql
,所以sql
現在是一個字符串,不再是一個保存write_frame
函數的pandas
模塊。
編輯: AttributeError: 'numpy.int64' object has no attribute 'replace'
錯誤你得到的是由於你使用整數列標簽(這是一個錯誤)。 嘗試將列標簽設置為其他內容,例如:
df.columns = ['COL1', 'COL2', 'COL3']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.