gpt4 book ai didi

python - 如何根据 pyodbc 查询的结果创建 NumPy 数组?

转载 作者:行者123 更新时间:2023-11-28 18:22:23 25 4
gpt4 key购买 nike

我想根据从 SQL 查询中提取的值创建一个数组或列表。根据研究,我相信我从 SQL 中提取的数据是一个元组。

如何将数据格式化为我可以在 python 中使用的列表?

在我当前的代码中,我尝试使用 numpy 命令 np.asarray。我不确定 numpy 数组是否允许日期时间。

import numpy as np
import pyodbc

conn = pyodbc.connect('login')
cursor = conn.cursor()
cursor.execute("SELECT PTIME, PVALUE FROM HISTORY_TABLE WHERE POINT = 'Value' AND PTIME> '2017-04-12' AND PTIME<'2017-04-13' AND HISTTYPE='AVG' AND PERIOD=7200")

sample = cursor.fetchall()
rockin = np.asarray(sample)
print rockin

cursor.close()
conn.close()

我的结果是这样的:

[[datetime.datetime(2017, 4, 12, 0, 0) 232.83]
[datetime.datetime(2017, 4, 12, 2, 0) 131.49]
[datetime.datetime(2017, 4, 12, 4, 0) 36.67]
...,
[datetime.datetime(2017, 4, 12, 18, 0) 82.08]
[datetime.datetime(2017, 4, 12, 20, 0) 368.83]
[datetime.datetime(2017, 4, 12, 22, 0) 435.79]]

最佳答案

From research I believe the data I pull from SQL is a tuple.

不完全是。 pyodbc 的 fetchall() 方法不返回元组列表,它返回 pyodbc.Row 对象列表:

>>> rows = crsr.execute("SELECT 1 AS foo UNION ALL SELECT 2 AS foo").fetchall()
>>> rows
[(1, ), (2, )]
>>> type(rows[0])
<type 'pyodbc.Row'>

可能是 np.asarray 不知道如何处理 pyodbc.Row 对象。如果你想将每一行转换为一个实际的元组,你可以使用

>>> rows_as_tuples = [tuple(x) for x in rows]
>>> rows_as_tuples
[(1,), (2,)]
>>> type(rows_as_tuples[0])
<type 'tuple'>

关于python - 如何根据 pyodbc 查询的结果创建 NumPy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44139234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com