Python以数组形式从MySQL导入列数据

Python以数组形式从MySQL导入列数据,python,numpy,mysql-python,Python,Numpy,Mysql Python,我有一段从mysql表中检索数据的代码。我正在使用Python的MySQLdb模块。我希望在数组下检索基于SELECT WHERE条件的每列数据。例如,在下面的代码中,我希望在不同的数组下检索位置字段为“NY,US”的所有数据,每个数组表示不同的列值 import numpy import MySQLdb db = MySQLdb.connect("localhost", "root", "", "test") cursor = db.cursor() sql = "SELECT * FRO

我有一段从mysql表中检索数据的代码。我正在使用Python的MySQLdb模块。我希望在数组下检索基于SELECT WHERE条件的每列数据。例如,在下面的代码中,我希望在不同的数组下检索位置字段为“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()

出现问题了吗?

一旦从
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) ) 

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()

discresults{}
在那里做什么?我想你需要使用commit()方法来完成查询。@shakabra acutallyy我编辑了一点这段代码。.以前它从每一列中取出一个值。这就是为什么这里有不谨慎的结果。你的问题不是很清楚。我不明白你的问题是什么。你到底想用上面的代码实现什么,而你却做不到?