【问题标题】:MySQLdb query to Numpy arrayMySQLdb 查询到 Numpy 数组
【发布时间】:2013-09-05 23:27:48
【问题描述】:

所以我尝试关注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.

知道我做错了什么吗?

【问题讨论】:

    标签: python mysql arrays numpy


    【解决方案1】:

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

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

    如果你所有的记录都是同一类型,那么你可以得到一个数组视图,如下所示:

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

    【讨论】:

    • 所以这主要是可行的,但由于它们是 bigint 数字,所以两行都是 numpy.uint32 而不是 numpy.uint8 。非常感谢!
    猜你喜欢
    • 2014-11-17
    • 2012-12-04
    • 2018-01-02
    • 2016-03-11
    • 2010-12-03
    • 1970-01-01
    • 2020-11-04
    • 2012-03-08
    • 2019-05-09
    相关资源
    最近更新 更多