0

I have a dataframe df and I tried converting dataframe to json as below:

from flask import Flask
import pandas as pd

app=Flask(__name__)

@app.route('/graph')
def plot():
    df=pd.DataFrame([['madrid', 10], ['venice', 20], ['las vegas', 40], ['brighton', 35]],
                      columns=['city', 'temp'])
    jsondata=df.to_json(orient='records')
    return jsondata

if __name__=='__main__':
    app.run()

o/p as follows:

[{"city":"madrid","temp":10},{"city":"venice","temp":20},{"city":"las vegas","temp":40},{"city":"brighton","temp":35}]

and if I use orient='split' o/p is :

{"columns":["city","temp"],"index":[0,1,2,3],"data":[["madrid",10],["venice",20],["las vegas",40],["brighton",35]]}

I am looking for an output as:

{
"trace1":[{"city":["madrid",....],"temp":[10,20,...]}]
}

No idea to get for city and temp as above ,but tried for trace1 atleast as return {"trace1":jsondata} but this is giving me

{
    "trace1": "{\"columns\":[\"city\",\"temp\"],\"index\":[0,1,2,3],\"data\":[[\"madrid\",10],[\"venice\",20],[\"las vegas\",40],[\"brighton\",35]]}"
}
0

1 Answer 1

2

Use DataFrame.to_dict with orient='list' for dictionary and then convert to json:

import json

jsondata= json.dumps({"trace1":[df.to_dict(orient='list')]})
print (jsondata)

{"trace1": [{"city": ["madrid", "venice", "las vegas", "brighton"],"temp": [10, 20, 40, 35]}]}
Sign up to request clarification or add additional context in comments.

7 Comments

Exactly what I'm looking for ...thanks jez
so couldn't we use df.to_json to achieve the same ??
@Codenewbie - it is not implemented, test df.to_json(orient='list')
ValueError: Invalid value 'list' for option 'orient'
@Codenewbie - I think there is double convert values to json, so second parsed json add `` for escape.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.