将数据帧转换为在flask python中作为“application-json”返回

Niz*_*Khs 9 python pandas

  dfList = df.values.tolist()
  return jsonify(dfList)
Run Code Online (Sandbox Code Playgroud)

我有这个结果,它实际上是删除 DataFrame 的变量名称并用整数替换它们

-0: [
  0: "Les abeilles sont dehors",
  1: "ObservationNature",
  2:  0.6790075732725341,
  3:  [],
],
-1:[
  0: "elle sont allée chercher le miel à coté des fleurs du rucher",
  1: "ObservationNature",
  2: 0.4250480624587389,
  3: [],
]
Run Code Online (Sandbox Code Playgroud)

我的结果应该是这样的,带有 DataFrame 中的变量

-0: [
  "texte": "Les abeilles sont dehors",
  "type": "ObservationNature",
  "nluScore":  0.6790075732725341,
  "ruche":  [],
],
-1:[
  "texte": "elle sont allée chercher le miel à coté des fleurs du rucher",
  "type": "ObservationNature",
  "nluScore": 0.4250480624587389,
  "ruche": [],
],
Run Code Online (Sandbox Code Playgroud)

Mai*_*ret 8

使用df.to_json()和设置mimetype='application/json'

例如:

from flask import Response
@app.route("/dfjson")
def dfjson():
    """
    return a json representation of the dataframe
    """
    df = get_dataframe_from_somewhere()
    return Response(df.to_json(orient="records"), mimetype='application/json')
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案!对于不同的json结构,请参考https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html (2认同)

A. *_*jar 5

那是因为您将 ndarray 类型传递给 jsonify。

尽管 df.to_json(orient="records") 将为您提供正确的服务,但您可以通过 df.iterrows() 和/或 defaultdit 实现您的特定格式这里是一个例子:

@app.route('/')
def pandasJSON():
    df2 = pd.DataFrame({'A': 1.,
                        'C': pd.Series(1, index=list(range(4)), dtype='float32'),
                        'D': np.array([3] * 4, dtype='int32'),
                        'E': pd.Categorical(["test", "train", "test", "train"]),                    
                        'F': 'foo'})

    df2['G'] = [100,200,300,400]
    df2.set_index('G', inplace=True)
    result = {}
    for index, row in df2.iterrows():
        #result[index] = row.to_json() 
        result[index] = dict(row)
    return jsonify(result)
Run Code Online (Sandbox Code Playgroud)

输出图像


小智 1

如果你跑

df.to_json(orient="records")
Run Code Online (Sandbox Code Playgroud)

它应该为您提供您想要的输出(注意:从 Pandas 版本 0.23.3 开始)