Pandas解析MySql结果

2024-10-05 11:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python在MySql上执行查询。在UI端使用FLOAPI表示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 ---

Tags: to数据方法fromuidatetimevalue
1条回答
网友
1楼 · 发布于 2024-10-05 11:23:16

问题是,如果将两列转换为整数的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')])

或者将fomrat更改为^{}l作为列表,然后使用zip和映射列表,最后转换为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()))))

相关问题 更多 >

    热门问题