使用下面的代碼,我可以從SQL中獲取行和列數據:
如何獲取表頭作爲結果集或數組的一部分。從python中獲取Numpy數組的SQL頭文件
top = csr.execute("Select * from bigtop")
d=list(top)
a = np.asarray(d, dtype='object')
print a
就像我在這裏問: How do I create a CSV file from database in Python?
使用下面的代碼,我可以從SQL中獲取行和列數據:
如何獲取表頭作爲結果集或數組的一部分。從python中獲取Numpy數組的SQL頭文件
top = csr.execute("Select * from bigtop")
d=list(top)
a = np.asarray(d, dtype='object')
print a
就像我在這裏問: How do I create a CSV file from database in Python?
如果你想要的列名數組中的第一行,你會做
top = csr.execute("Select * from bigtop")
d=list(top)
a = np.asarray([[x[0] for x in top.description]] + d, dtype='object')
,並得到類似
array([[heading1, heading2, heading3, ...],
[val1, val2, val3, ...],
...
, dtype=object)
csr.description
應該有頭
我認爲在這種情況下應該是'top.description'。 – 2011-05-05 20:02:03
,以及我如何將數據轉化爲numpy? – Merlin 2011-05-05 20:02:15
我不確定你的意思是「把它變成numpy」(它只是數據類型,對嗎?),但我認爲'np.asarray(top.description).T [0]'會做你的想。 – 2011-05-05 20:23:44
這是一個自包含的例子,說明了總體思路。 numpy.recarray
是你的朋友,
from sqlite3 import connect
from numpy import asarray
db = connect(":memory:")
c = db.cursor()
c.execute('create table bigtop (a int, b int, c int)')
for v in [(1,2,3),(4,5,6),(7,8,9)]:
c.execute('insert into bigtop values (?,?,?)',v)
s = c.execute('select * from bigtop')
h = [(i[0],int) for i in c.description]
# You can also use 'object' for your type
# h = [(i[0],object) for i in c.description]
a = asarray(list(s),dtype=h)
print a['a']
給人的第一列,
[1 4 7]
,並
print a.dtype
給出了每列名稱和類型,
[('a', '<i4'), ('b', '<i4'), ('c', '<i4')]
或者,如果你使用過object
爲你的類型,你得到的,
[('a', '|O4'), ('b', '|O4'), ('c', '|O4')]
但我喜歡lafrasu將標題名稱放入dtype名稱的想法,您可以通過'a.dtype.names'訪問它。然後您可以通過代碼中的數字*或*名稱索引列。 – 2011-05-06 13:36:28