将 Pandas 数据帧作为 Python Flask 中的 JSONP 响应返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42309133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:00:57  来源:igfitidea点击:

Return Pandas dataframe as JSONP response in Python Flask

pythonjsonpandasflaskjsonp

提问by baermathias

I want to return data as JSONPresponse in Flask.

我想JSONPFlask.

The data comes from a Pandas dataframeand I can return it as JSONwith the following line:

数据来自 a Pandas dataframe,我可以像JSON下面这样返回它:

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 ]]

But I need it as JSONP, so I use the following code:

但我需要它作为JSONP,所以我使用以下代码:

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,1038,103,104,10,104,108,104,100,100,104,104,104,104,104,104,103,104,104,1000,100000,1042,1042,1038,1038,1038,1040,104,108 17.8684]]”

How can I get the JSONPresponse in Flaskwithout double quotes? Many thanks in advance.

如何JSONPFlask没有双引号的情况下获得响应?提前谢谢了。

回答by baermathias

This is my solution to convert a Pandas dataframe to JSONP an return it in Flask:

这是我将 Pandas 数据帧转换为 JSONP 并在 Flask 中返回它的解决方案:

from flask_jsonpify import jsonpify
df_list = df.values.tolist()
JSONP_data = jsonpify(df_list)
return JSONP_data

Depending on how you need the dataframe converted, you might need to create the list in a different way. For example like this:

根据您需要如何转换数据框,您可能需要以不同的方式创建列表。例如像这样:

df_list = merged.values.T.tolist() 

Or like this:

或者像这样:

df_list = list(df.values.flatten())

Thanks goes to the user @Barmer

感谢用户@Barmer