首页 > 解决方案 > 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 ---

标签: pythonmysqlpandasdataframe

解决方案


问题是,如果将两列都转换为整数的 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,然后使用zipwith 映射列表,最后转换为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()))))

推荐阅读