2011-05-05 19 views

回答

1

如果你想要的列名數組中的第一行,你會做

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) 
+1

但我喜歡lafrasu將標題名稱放入dtype名稱的想法,您可以通過'a.dtype.names'訪問它。然後您可以通過代碼中的數字*或*名稱索引列。 – 2011-05-06 13:36:28

2

csr.description應該有頭

+0

我認爲在這種情況下應該是'top.description'。 – 2011-05-05 20:02:03

+0

,以及我如何將數據轉化爲numpy? – Merlin 2011-05-05 20:02:15

+0

我不確定你的意思是「把它變成numpy」(它只是數據類型,對嗎?),但我認爲'np.asarray(top.description).T [0]'會做你的想。 – 2011-05-05 20:23:44

4

這是一個自包含的例子,說明了總體思路。 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')] 
+1

就像事後想想的那樣,您可能需要考慮類似[pytables](http://www.pytables.org/moin)或[h5py](http://code.google.com/p/h5py/)if你想存儲數字型數據。特別是如果你想'numpy'的支持。 – lafras 2011-05-06 00:05:11

+0

@ user428862:這是正確的,表中的第一列。 – lafras 2011-05-06 00:36:39

+0

@lafrasu。請再次讀q。我想把Sql頭作爲數組的一部分。在你的前。它會a,b,c – Merlin 2011-05-06 00:49:37