Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert dataframe to be returned as "application-json" in flask python

Tags:

python

pandas

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

I have this as result, it's actualy removing the variable names of the DataFrame and replacing them with integers

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

my result should look like this, with the varibales that are in the 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": [],
],
like image 740
Nizar Khs Avatar asked Jul 17 '18 10:07

Nizar Khs


3 Answers

Use df.to_json() and set mimetype='application/json'

for example:

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')
like image 167
Savrige Avatar answered Nov 04 '22 15:11

Savrige


That's because you're passing ndarray type to jsonify.

Although df.to_json(orient="records") will serve you right, you can achieve your specific format through df.iterrows() and/or defaultdit Here is an example:

@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

like image 41
A. Nadjar Avatar answered Nov 04 '22 14:11

A. Nadjar


If you run

df.to_json(orient="records")

it should provide you with the output that you want (note: as of Pandas version 0.23.3)

like image 35
Kevin Li Avatar answered Nov 04 '22 15:11

Kevin Li