Pandas Dataframe to Nested JSON

前端 未结 3 1786
余生分开走
余生分开走 2020-12-14 23:32

I am trying to convert a Pandas Dataframe to a JSON object. My Dataframe contains data in the following format:

         student      date    grade                  


        
3条回答
  •  北海茫月
    2020-12-14 23:46

    You can first define a function to convert sub-groups to json, then apply this function to each group, and then merge sub-group jsons to a single json object.

    def f(x):
        return (dict({'date':x.date.iloc[0]},**{k:v for k,v in zip(x.student,x.grade)}))
    
    (
        df.groupby(['course','date'])
          .apply(f)
          .groupby(level=0)
          .apply(lambda x: x.tolist())
          .to_dict()
    )
    Out[1006]: 
    {'ENGLISH': [{'Student_1': 93, 'Student_2': 83, 'date': '2017-06-25'},
      {'Student_1': 96, 'Student_2': 99, 'date': '2017-06-26'}],
     'MATH': [{'Student_1': 93, 'Student_2': 83, 'date': '2017-06-25'},
      {'Student_1': 90, 'Student_2': 85, 'date': '2017-06-26'}]}
    

提交回复
热议问题