MySQLdb查询到Numpy数组

时间:2013-09-02 20:20:35

标签: python mysql arrays numpy

所以我试图关注What's the most efficient way to convert a MySQL result set to a NumPy array?,但仍然遇到问题。

我的数据库行是57个无符号整数(Unix纪元加上28个交换机端口中的每一个的字节数,进出)。

我的代码如下:

import MySQLdb as mdb
import numpy

# get the database connector
DBconn = mdb.connect('localhost', 'root', '<Password>', 'Monitoring')

with DBconn:

    # prepare a cursor object using cursor() method
    cursor = DBconn.cursor()

    # now get the data for the last 10 minutes
    sql = "select * from LowerSwitchBytes where ComputerTime >= (unix_timestamp(now())-(60*10))"
    cursor.execute(sql)

    results = cursor.fetchall()
    for row in results:
        print row

所以打印出10行,如:

(1378151928L, 615983307L, 517980853L, 25355784L, 117110102L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 267680651L, 288368872L, 84761960L, 337403085L, 224270992L, 335381466L, 27238950843L, 549910918625L, 240002569249L, 11167210734L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 222575491L, 335850213L, 223669465L, 339800088L, 310004136202L, 16635727254L, 0L, 0L, 16590672L, 147102083L, 0L, 0L, 0L, 0L)

但是当我改变:

    results = cursor.fetchall()
    for row in results:
        print row

    A = numpy.fromiter(cursor.fetchall(), count=-1, dtype=numpy.uint32)
    print A

我明白了:

Traceback (most recent call last):
  File "min.py", line 23, in <module>
    A = numpy.fromiter(cursor.fetchall(), count=-1, dtype=numpy.uint32)
ValueError: setting an array element with a sequence.

知道我做错了吗?

1 个答案:

答案 0 :(得分:2)

np.fromiter抱怨是因为它试图将一整行输入写入新数组的单个项目中。您可以使用记录数组解决此问题:

A = numpy.fromiter(cursor.fetchall(), count=-1,
                   dtype=[('', numpy.uint8)]*57)

如果您的所有记录属于同一类型,则可以按如下方式获取数组视图:

A = A.view(numpy.uint8).reshape(-1, 57)