简体   繁体   English

将numpy数组放入Mysql db的最快和最有效的方法

[英]Fastest and most efficient way to put a numpy array to Mysql db

So I have a two numpy array. 所以我有两个numpy数组。 One of the arrays contain the object_ids for my database and all of these are ints and another contains the values I want to put to my database which are floats. 数组之一包含我数据库的object_id,所有这些都是整数,另一个数组包含我要放入数据库的浮点值。 Also my database is a mysql db. 我的数据库也是mysql db。

what is the most efficient way to put all of this to my mysql db cause Im looking to optimize my code. 将所有这些都放到我的mysql数据库中的最有效方法是什么,原因是Im希望优化我的代码。

im also using MySQLdb and cursors to connect to my database. 我还使用MySQLdb和游标连接到我的数据库。

You can use pandas as a clean interface between the two worlds. 您可以将pandas用作两个世界之间的干净接口。 As an example : 举个例子 :

import numpy as np
import pandas as pd

index = np.arange(10)
values = np.random.rand(10,2)
names= ['a','b']

df= pd.DataFrame(values,index,names)

In [217]: df
Out[217]: 
          a         b
0  0.259787  0.313253
1  0.449761  0.363243
2  0.916497  0.204994
3  0.168862  0.718966
4  0.248206  0.106945
5  0.709540  0.902679
6  0.413442  0.933243
7  0.568530  0.427908
8  0.926834  0.967445
9  0.175371  0.952798

You can then use df.to_sql which will tranfer you data in a SQL database. 然后,您可以使用df.to_sql ,它将在SQL数据库中传输数据。

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

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