Python从MySQL导入列数据作为数组

时间:2012-11-17 06:31:08

标签: python numpy mysql-python

我有这个代码从mysql表中检索数据。我正在使用Python的MySQLdb模块。我希望在数组下检索基于SELECT WHERE条件的EACH列的数据。例如,在下面的代码中,我希望在不同的数组下检索位置字段为“NY,US”的所有数据 - 每个数组代表不同的列值。

import numpy
import MySQLdb

db = MySQLdb.connect("localhost", "root", "", "test")
cursor = db.cursor()

sql = "SELECT * FROM usa_new WHERE location = 'NY, US'"
try:
   cursor.execute(sql)
   results = cursor.fetchall()
   discresults = {}
   for row in results:

      id = row[0]
      location = row[1]
      temp_f = row[2]
      pressure_mb = row[3]
      wind_dir = row[4]
      wind_mph = row[5]
      relative_humidity = row[6]
      timestamp = row[7]

except:
   print "Error: unable to fecth data"

db.close()

有什么问题吗?

2 个答案:

答案 0 :(得分:2)

python中有一个名为'list'的数据结构,可以用作数组。 如果你的问题是我所理解的语义 “将结果存储在按列分类的数组中,以存储在本地列表中”,所以这里有一个简单的实现: 记得我已经按照给定的标准逐个获取行;这是一个很好的做法;

import MySQLdb

db = MySQLdb.connect("localhost", "root", "", "test")
cursor = db.cursor()
id, location, temp_fm, pressure_mb, .. = [],[],[],[],...
//for the number of lists you want to create, just add their names and a empty list
sql = "SELECT * FROM usa_new WHERE location = 'NY, US'"

try:
   cursor.execute(sql)

   rcount = int(cursor.rowcount)

   for r in rcount:
      row = cursor.fetchone()

      id.append(row[0])
      location.append(row[1])
      temp_f.append(row[2])
      pressure_mb.append(row[3])
      wind_dir.append(row[4])
      wind_mph.append(row[5])
      relative_humidity.append(row[6])
      timestamp.append(row[7])

except:
   print "Error: unable to fecth data"

db.close()

答案 1 :(得分:0)

results获得cursor.fetchall()后,您可以尝试将结果映射为numpy数组: -

cols = zip( *results ) # return a list of each column
                      # ( the * unpacks the 1st level of the tuple )
outlist = []

for col in cols:

    arr = numpy.asarray( col )

    type = arr.dtype

    if str(type)[0:2] == '|S':
        # it's a string array!
        outlist.append( arr )
    else:
        outlist.append( numpy.asarray(arr, numpy.float32) )