首页 > 解决方案 > 基于列的字符串到熊猫数据框

问题描述

我正在向烧瓶服务器 ( http://localhost:5000/req/?q=139,2,10,60,5,1462,7,5,6,9,17,78) 发送一个 ajax GET 请求,以便检索一些值并将它们分配给 Dataframe。手动操作,效果很好:

df = pd.DataFrame(data=[[139,2,10,60,5,1462,7,5,6,9,17,78]],columns=['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10','col11','col12'])

但我需要通过 ajax 来自request.args的数字,然后作为数组基于 Dataframe。

@app.route('/req/', methods=['GET'])
def foo():
    args = dict(request.args.to_dict())
    t = request.args["q"]
    return getResults(t), 200

getResults() 类似于:

def getResults(name):
    df = pd.DataFrame(data=[[name]], columns=['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10','col11','col12'])
    """"

但这当然行不通。给出错误:ValueError: 12 列已通过,传递的数据有 1 列

我怎样才能做到这一点 ?我试过拆分字符串,尝试转换为数组..没有任何效果。

标签: pythonpandasnumpydataframeflask

解决方案


args 被解析为字符串,因此在t = request.args["q"], tis之后"139,2,10,60,5,1462,7,5,6,9,17,78",您需要一个 int 列表

@app.route('/req') # GET only is default method
def foo():
    t = request.args["q"]
    t = [int(val) for val in t.split(",")]
    return getResults(t) # 200 is the default status code

def getResults(name):
    df = pd.DataFrame(data=[name], # no extra []

Also prefer /req (that allows both with and without trailing slash) rather than /req/ that accept only one , refer to this for detail


推荐阅读