使用下面的命令,我可以从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?
发布于 2011-05-06 21:29:57
如果您希望列名作为数组中的第一行,您可以这样做
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)发布于 2011-05-06 08:01:13
这是一个自包含的示例,说明了一般概念。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')]发布于 2011-05-06 03:51:21
csr.description应该有标头
https://stackoverflow.com/questions/5903288
复制相似问题