Creating complex nested dictionaries from Pandas DataFrame

后端 未结 2 1188
梦毁少年i
梦毁少年i 2021-01-13 02:28

I\'m trying to find a generic way of creating (possibly deeply) nested dictionaries from a flat Pandas DataFrame instance.

Suppose I have the following DataFrame:

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-13 02:56

    This is partial answer. I don't know how to convert the index to json.

    df = pd.DataFrame({'name' : ['John', 'John', 'John', 'John', 'Henry', 'Henry'],
                        'age' : [24, 24, 24, 24, 31, 31],
                        'gender' : ['Male','Male','Male','Male','Male','Male'],
                        'study' : ['Mathematics', 'Mathematics', 'Mathematics', 'Philosophy', 'Physics', 'Physics'],
                        'course' : ['Calculus 101', 'Calculus 101', 'Calculus 102', 'Aristotelean Ethics', 'Quantum mechanics', 'Quantum mechanics'],
                        'test' : ['Exam', 'Essay','Exam','Essay', 'Exam1','Exam2'],
                        'pass' : [True, True, True, True, True, True],
                        'grade' : ['A', 'A', 'B', 'A', 'C', 'C']})
    df.set_index(keys=['name','age','gender', 'study','course','test','grade','pass'], inplace=True)
    df
    

    Output:

提交回复
热议问题