【问题标题】:Get SQL headers from Numpy Array in python从 python 中的 Numpy 数组获取 SQL 标头
【发布时间】:2011-08-19 16:26:17
【问题描述】:

通过下面,我可以从 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?

【问题讨论】:

    标签: python sql numpy


    【解决方案1】:

    这是一个自包含的示例,说明了总体思路。 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')]
    

    【讨论】:

    • 如果您想存储数字类型数据,您可能需要考虑类似pytablesh5py 之类的东西。特别是如果你想要numpy 支持。
    • @lafrasu。请再读一遍q。我希望 Sql 标头作为数组的一部分。在你的前任。它会a,b,c
    • @user428862:我看到你改变了问题,但我不确定我是否完全理解你想要什么?一旦你有了一个数组,你就可以通过数组的dtype 属性访问“标题”。
    • 向我展示:“通过数组的 dtype 属性访问 'headers'。”。数组是 dtype='object'。我正在将一个数组中的完整表头和数据作为一个包。
    【解决方案2】:

    csr.description 应该有标题

    【讨论】:

    • 我认为在这种情况下应该是top.description
    • 以及,我如何将这些数据导入 numpy?
    • 我不确定你所说的“把它变成 numpy”是什么意思(只是数据类型,对吧?),但我认为 np.asarray(top.description).T[0] 会做你想做的事。
    • 如何组合这两个数组?
    【解决方案3】:

    如果您希望列名作为数组中的第一行,您可以这样做

    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)
    

    【讨论】:

    • 但我喜欢 lafrasu 将标题名称放入 dtype 名称中的想法,您可以通过 a.dtype.names 访问它。然后您可以在代码中按数字名称对列进行索引。
    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 2011-08-11
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    相关资源
    最近更新 更多