Skip to content Skip to sidebar Skip to footer

A Dataframe With Two Index To Json In Pandas

I'am trying to convert pandas' dataFrame to json. y=pd.read_csv('testx.csv',encoding='utf-8') y.columns = ['i','city','language','words'] del y['i'] y = y.set_index(['city','langua

Solution 1:

Would you be willing to use a dict comprehension to explicitly craft your output? You can then use json.dumps to convert from python dict to JSON. Your desired form is unfortunately outside the standard outputs that to_json supports.

[{"city":i, 
  "language":{l:n 
      for l,n in zip(g['language'], g['words'])}} 
   for i,g in df.groupby('city')] 
[{'city': 'London',
  'language': {'English': 9100000, 'Russian': 150000, 'Spanish': 90000}},
 {'city': 'Moscow',
  'language': {'English': 550000, 'French': 100000, 'Russian': 3300000}}]

Post a Comment for "A Dataframe With Two Index To Json In Pandas"