在Python Flask中将Pandas数据帧返回为JSONP响应 [英] Return Pandas dataframe as JSONP response in Python Flask
问题描述
我想返回数据作为Flask
中的JSONP
响应.
I want to return data as JSONP
response in Flask
.
数据来自Pandas dataframe
,我可以使用以下行将其作为JSON
返回:
The data comes from a Pandas dataframe
and I can return it as JSON
with the following line:
json_data = dataframe.to_json(orient='values')
return json_data
工作正常,我得到了数据,看起来像这样:
Works fine and I get the data, which looks like this:
[[1487310600000,1038,1042,1038,1038,-2.243,6.8933],[1487310900000,1042,1042,1038,1038,-1.3626,4.3058],[1487311200000,1042,1042,1038,1038,- 1.4631,17.8684]]
[[1487310600000,1038,1042,1038,1038,-2.243,6.8933],[1487310900000,1042,1042,1038,1038,-1.3626,4.3058],[1487311200000,1042,1042,1038,1038,-1.4631,17.8684]]
但是我需要它作为JSONP
,所以我使用以下代码:
But I need it as JSONP
, so I use the following code:
from flask_jsonpify import jsonpify
json_data = dataframe.to_json(orient='values')
return jsonpify(json_data)
它给了我数据,但带双引号:
And it gives me the data, but with double quotes:
"[[[1487310600000,1038,1042,1038,1038,-2.243,6.8933],[1487310900000,1042,1042,1038,1038,-1.3626,4.3058],[1487311200000,1042,1042,1038,1038, -1.4631,17.8684]]"
"[[1487310600000,1038,1042,1038,1038,-2.243,6.8933],[1487310900000,1042,1042,1038,1038,-1.3626,4.3058],[1487311200000,1042,1042,1038,1038,-1.4631,17.8684]]"
如何在Flask
中不带双引号的情况下得到JSONP
响应?
预先非常感谢.
How can I get the JSONP
response in Flask
without double quotes?
Many thanks in advance.
推荐答案
这是将熊猫数据框转换为JSONP并在Flask中返回的解决方案:
This is my solution to convert a Pandas dataframe to JSONP an return it in Flask:
from flask_jsonpify import jsonpify
df_list = df.values.tolist()
JSONP_data = jsonpify(df_list)
return JSONP_data
根据您需要如何转换数据框,您可能需要以与我不同的方式制作列表,例如像这样的df_list = merged.values.T.tolist()
或这样的df_list = list(df.values.flatten())
等.
Depending on how you need the dataframe converted, you might need to make the list in a different way as me, e.g. like this df_list = merged.values.T.tolist()
or like this df_list = list(df.values.flatten())
etc.
感谢用户@Barmer
Thanks goes to the user @Barmer
这篇关于在Python Flask中将Pandas数据帧返回为JSONP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!