python - pandas - 解析 MySql 结果
问题描述
我正在使用 python pandas 在 MySql 上执行查询。在 UI 端使用 Flot API 来表示 MySql 数据。下面是现有的实现,
query2 = f"""select time, value from NWSTAT
where time > \'{from_date}\'
and time < \'{to_date}\'"""
result2 = pd.read_sql(query2, engine)
return result2.to_json(orient='records')
得到以下格式的结果
[{"time": 1581931200000, "value": 0.0}, {"time": 1581931200000, "value": 0.0},
{"time": 1581931200000, "value": 0.0}, {"time": 1581931200000, "value": 0.0}]
从这个响应中,我在 UI Javascript 端为 Flot API 创建了 belwo 结构,
[[1581931200000,0],[1581931200000,0],[1581931200000,0],[1581931200000,0]]
有没有什么方法可以在没有任何迭代的情况下在 python 端做到这一点?直接来自查询结果。
使用 Flask 服务器。UI端:JQuery、Handlebar JS
编辑:在接受的答案中,第二种方法需要更少的时间.. 以下是 240k 记录的两种方法所用的时间
First one: --- 1.6689300537109375e-06 seconds ---
Second one: --- 0.5330650806427002 seconds ---
解决方案
问题是,如果将两列都转换为整数的 numpy 数组格式,则将其更改为浮点数。
print (json.dumps(result2.to_numpy().tolist()))
第一个想法是从.values()
字典创建列表并转换为json
:
import json
query2 = f"""select time, value from NWSTAT
where time > \'{from_date}\'
and time < \'{to_date}\'"""
result2 = pd.read_sql(query2, engine)
return json.dumps([list(x.values()) for x in result2.to_dict(orient='records')])
DataFrame.to_dict
或通过with for 列表更改 fomrat l
,然后使用zip
with 映射列表,最后转换为json
:
import json
query2 = f"""select time, value from NWSTAT
where time > \'{from_date}\'
and time < \'{to_date}\'"""
result2 = pd.read_sql(query2, engine)
return json.dumps(list(map(list, zip(*result2.to_dict(orient='l').values()))))
推荐阅读
- google-cloud-platform - (谷歌云平台)我不小心在Linux VM里面设置了防火墙
- hierarchical-data - Azure SQL DB - 分层查询
- dataframe - Pyspark 中最多两列
- discord - TypeError:制作爆炸参数时无法读取未定义的属性“bulkDelete”
- node.js - 如何使用 React Error boundry get error details 尽可能多地获取有关错误的详细信息?
- android - 房间自动迁移不起作用:新表(实体)的致命异常
- docker - 如何在同一个 docker 容器中运行 nginx 和 gunicorn
- pandas - 在熊猫 1.3 中升级多索引数据帧
- excel - VBA编码,查找和匹配功能
- javascript - 如何在 javascript 中删除元素?