【发布时间】:2017-08-25 17:35:39
【问题描述】:
我正在使用 python 将一个大矩阵(形状约为 3000 * 3000)导出到 MySQL。
现在我正在使用 MySQLdb 来插入这些值,但它太麻烦而且效率太低。这是我的代码:
# -*- coding:utf-8 -*-
import MySQLdb
import numpy as np
import pandas as pd
import time
def feature_to_sql_format(df):
df = df.fillna(value='')
columns = list(df.columns)
index = list(df.index)
index_sort = np.reshape([[int(i)] * len(columns) for i in index], (-1)).tolist()
columns_sort = (columns * len(index))
values_sort = df.values.reshape(-1).tolist()
return str(zip(index_sort, columns_sort, values_sort))[1: -1].replace("'NULL'", 'NULL')
if __name__ == '__main__':
t1 = time.clock()
df = pd.read_csv('C:\\test.csv', header=0, index_col=0)
output_string = feature_to_sql_format(df)
sql_CreateTable = 'USE derivative_pool;DROP TABLE IF exists test1;' \
'CREATE TABLE test1(date INT NOT NULL, code VARCHAR(12) NOT NULL, value FLOAT NULL);'
sql_Insert = 'INSERT INTO test (date,code,value) VALUES ' + output_string + ';'
con = MySQLdb.connect(......)
cur = con.cursor()
cur.execute(sql_CreateTable)
cur.close()
cur = con.cursor()
cur.execute(sql_Insert)
cur.close()
con.commit()
con.close()
t2 = time.clock()
print t2 - t1
它总共消耗大约 274 秒。
我想知道是否有更简单的方法可以做到这一点,我想到了将矩阵导出到csv然后使用LOAD DATA INFILE来导入,但它也太复杂了。
我注意到在pandas文档中pandas dataframe有一个函数to_sql,在version 0.14你可以将'flavor'设置为'mysql',即:
df.to_sql(con=con, name=name, flavor='mysql')
但是现在我的pandas版本是0.19.2,味道也降到只有'sqlite'了……而且我还在尝试使用
df.to_sql(con=con, name=name, flavor='sqlite')
它给了我一个错误。
有什么方便的方法吗?
【问题讨论】:
标签: mysql python-2.7 pandas mysql-python