dataframe - 如何将 presto 查询输出转换为 python 数据框
问题描述
我想将我的查询输出转换为 python 数据框以绘制折线图
import prestodb
import pandas as pd
conn=prestodb.dbapi.connect(
host='10.0.0.101',
port=8081,
user='hive',
catalog='hive',
schema='ong',
)
cur = conn.cursor()
query="SELECT dtime,tagName FROM machine where tagname is not null
limit 1000"
cur.execute(query)
rows = cur.fetchall()
print(rows)
df = pd.DataFrame(query, columns=['x_axis','tagName'])
这是我的查询示例输出
[['2018-09-08 00:00:00.000', 26], ['2018-09-08 01:00:00.000', 26],
['2018-09-08 02:00:00.000', 26], ['2018-09-08 03:00:00.000', 27],
['2018-09-08 04:00:00.000', 27], ['2018-09-08 05:00:00.000', 27]]
如何使用python将此查询输出转换为数据框
解决方案
这很简单,我建议您使用pyhive.presto
连接器(请参阅:https ://github.com/dropbox/PyHive )连接到 presto,但您使用的连接器也应该以相同的方式工作。
然后你有几个选择:
1 - 使用 presto 连接和 pandasread_sql_query
2 - 使用 presto cursor 并使用 fetchall 的输出作为数据帧的输入数据。
# option 1
import pandas as pd
from pyhive import presto
connection = presto.connect(user='my-user', host='presto.my.host.com', port=8889)
df = pd.read_sql_query("select 100", connection)
print(
df.head()
)
或者
# option 2
import pandas as pd
from pyhive import presto
connection = presto.connect(user='my-user', host='presto.my.host.com', port=8889)
cur = connection.cursor()
cur.execute("select 100")
df = pd.DataFrame(cur.fetchall())
print(
df.head()
)
推荐阅读
- multithreading - 进程结束时内核级线程会发生什么?
- sql - 如何将一个表格行作为其他表格列加入以用作动态值?
- android - 引起:groovy.lang.MissingMethodException:没有方法签名:com.android.build.gradle.AppPlugin.getVariantManager()
- r - 使用 2 列中的值匹配进行变异
- r - 根据条件创建二元对数据集
- python - pandas 中 .prod 的结果给了我一个 inf 编号,我怎样才能看到结果
- node.js - Heroku MERN 堆栈环境变量
- r - R分割代表指定距离的路线的SpatialLinesDataFrame
- git - 在 Git 中硬重置后,有没有办法截断分支,使其不反映快进?
- wso2esb - 如何从 config.properties 文件将端点添加到 wso2 esb rest api?