dfList = df.values.tolist()
return jsonify(dfList)
我有这个结果,它实际上删除了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: [],
]
我的结果应该是这样的,使用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": [],
],
df.to_json(orient='records')
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
使用'index'格式化的JSON对Dataframe进行编码/解码:
df.to_json(orient='index')
'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
使用'columns'格式化的JSON对Dataframe进行编码/解码:
df.to_json(orient='columns')
'{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'
使用'values'格式化的JSON对Dataframe进行编码/解码:
df.to_json(orient='values')
'[["a","b"],["c","d"]]'
那是因为你将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)
如果你跑
df.to_json(orient="records")
它应该为您提供所需的输出(注意:从Pandas版本0.23.3开始)