Get SQL headers from a Numpy array in python

Below I can get row and column data from SQL:
How to get table headers as part of a result set or array.?

    top = csr.execute("Select * from bigtop")
    d=list(top)
    a = np.asarray(d, dtype='object')
    print a

Just as I asked here: How to create a CSV file from a database in Python?

+5
source share
3 answers

If you want the column names to be the first row in your array, you would do

top = csr.execute("Select * from bigtop")
d=list(top)
a = np.asarray([[x[0] for x in top.description]] + d, dtype='object')

and get something like

array([[heading1, heading2, heading3, ...],
       [val1, val2, val3, ...],
           ...
           , dtype=object)
+1
source

This is a self-sufficient example illustrating a general idea. numpy.recarray- your friend,

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']

gives the first column,

[1 4 7]

and

print a.dtype

gives the name and type of each column,

[('a', '<i4'), ('b', '<i4'), ('c', '<i4')]

, object ,

[('a', '|O4'), ('b', '|O4'), ('c', '|O4')]
+4

csr.description

+2
source

All Articles