将Numpy数组插入Mysql数据库

时间:2011-08-12 16:17:58

标签: python mysql database arrays numpy

首先回答:

Using Numpy to create Yahoo finance price table

import numpy as np
import pylab as pl
import urllib
url = "http://ichart.yahoo.com/table.csv?a=2&c=2011&b=30&e=7&d=7&g=d&f=2011&s=msft&ignore=.csv"
f = urllib.urlopen(url)
title = f.readline().strip().split(",")
data = np.loadtxt(f, dtype=np.float, delimiter=",", converters={0: pl.datestr2num})

我想将返回行插入db。 数据如下所示:

 [[734233.0 25.98 26.31 25.86 26.15 65581400 25.98]
 [734232.0 25.82 26.18 25.74 25.78 73694500 25.61]
 [734231.0 25.45 25.66 25.41 25.55 35433700 25.38]
 [734228.0 25.53 25.53 25.31 25.48 63114200 25.31]
 [734227.0 25.60 25.68 25.34 25.39 63233700 25.22]
 [734226.0 25.60 25.72 25.50 25.61 41999300 25.44]]

我如何将这个numpy数组解析为列表或表,以便我可以插入到数据库中。请注意,所有行都不是分开的,而是一行。数据库部分有效。

data.tolist()不解析单行

寻找像

这样的输出
    [[734233.0 ,25.98 ,26.31 ,25.86 ,26.15, 65581400, 25.98]  
     [734232.0, 25.82, 26.18, 25.74, 25.78, 73694500, 25.61]
     [734231.0, 25.45 ,25.66, 25.41, 25.55, 35433700, 25.38]
     [734228.0, 25.53, 25.53, 25.31, 25.48, 63114200, 25.31]
     [734227.0, 25.60 ,25.68, 25.34, 25.39, 63233700, 25.22]
     [734226.0, 25.60, 25.72, 25.50, 25.61, 41999300, 25.44]]

用“,”代替“”吗?

2 个答案:

答案 0 :(得分:2)

>>> import sqlalchemy as sa
>>> import numpy as np
>>> import time, datetime
>>> import urllib

与日期格式之间的转换。

>>> datestr2timestamp = lambda d: time.mktime(time.strptime(d,"%Y-%m-%d"))
>>> def npvector_to_sadict(vector):
...     row = dict(zip(("open", "high", "low", "close", "volume", "adj_close"),
...                        vector[1:]))
...     row['date'] = datetime.date.fromtimestamp(vector[0])
...     return row
... 

从网络资源加载数据:

>>> url = "http://ichart.yahoo.com/table.csv?a=2&c=2011&b=30&e=7&d=7&g=d&f=2011&s=msft&ignore=.csv"
>>> f = urllib.urlopen(url)
>>> title = f.readline().strip().split(",")
>>> data = np.loadtxt(f, dtype=np.float, delimiter=",", converters={0: datestr2timestamp})

定义数据库表的外观

>>> metadata = sa.MetaData()
>>> stockdata = sa.Table('stockdata', metadata,
...                      sa.Column('date', sa.Date),
...                      sa.Column('open', sa.Float),
...                      sa.Column('high', sa.Float),
...                      sa.Column('low', sa.Float),
...                      sa.Column('close', sa.Float),
...                      sa.Column('volume', sa.Float),
...                      sa.Column('adj_close', sa.Float))

连接数据库。您可以将此更改为mysql://user:password@host/以获取mysql数据库

>>> engine = sa.create_engine("sqlite:///:memory:")

仅用于演示,如果您已经创建了表格,请跳过此步骤。

>>> metadata.create_all(engine)

将数据插入数据库:

>>> engine.execute(stockdata.insert(), [npvector_to_sadict(datum) for datum in data])
<sqlalchemy.engine.base.ResultProxy object at 0x23ea150>

确认已插入

>>> print data.shape[0], engine.execute(sa.select([sa.func.count(stockdata.c.close)])).scalar()
90 90
>>> 

答案 1 :(得分:1)

所以你有一行看起来像"[734226.0 25.60 25.72 25.50 25.61 41999300 25.44]"的字符串,你想把它转换成一个包含各个值的列表?这样的事情可以解决问题:

my_string = "[734226.0 25.60 25.72 25.50 25.61 41999300 25.44]"
my_list = [float(s) for s in my_string[1:-1].split(' ')]

为什么你不能这样做:

for row in data:
    print row #do whatever you want with row here.