在flaskpython中将dataframe转换为“applicationjson”返回

2024-10-06 07:07:11 发布

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

  dfList = df.values.tolist()
  return jsonify(dfList)

结果是,它实际上删除了数据帧的变量名,并用整数替换它们

^{pr2}$

我的结果应该是这样的,包括数据帧中的变量

-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": [],
],

Tags: 数据dfreturntype整数valuesjsonifytolist
3条回答

这是因为要将ndarray类型传递给jsonify。在

尽管df.to_json文件(orient=“records”)将为您服务, 您可以通过数据框错误()和/或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)

Output Image

如果你跑了

df.to_json(orient="records")

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

查找pandas documentation

df.to_json(orient='records')
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'

使用“index”格式的JSON对数据帧进行编码/解码:

^{pr2}$

使用“columns”格式的JSON对数据帧进行编码/解码:

df.to_json(orient='columns')
'{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'

使用“values”格式的JSON对数据帧进行编码/解码:

df.to_json(orient='values')
'[["a","b"],["c","d"]]'

相关问题 更多 >