Pandas Dataframe to Nested JSON

前端 未结 3 1794
余生分开走
余生分开走 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-15 00:07

    If you first have multiples indexes in your DataFrame and you do myDataframe.to_dict(orient='index') then it will create a dictionary where key=tuple and value="the remaining non-indexed columns".

    You can simply create a recursive function that will create a dict as nested as the number of elements in the tuple key as follows:

    def recurse(test):
        lentpl=len(list(test.keys())[0])
        if lentpl==2:
            return {k[0]:{k[1]:v} for k,v in test.items()}
        else:
            test2={k[0:-1]:{k[-1]:v} for k,v in test.items()}
            return recurse(test2)
    

提交回复
热议问题