Construct pandas DataFrame from items in nested dictionary

后端 未结 5 1858
名媛妹妹
名媛妹妹 2020-11-22 10:49

Suppose I have a nested dictionary \'user_dict\' with structure:

  • Level 1: UserId (Long Integer)
  • Level 2: Category (S
5条回答
  •  心在旅途
    2020-11-22 11:19

    pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

    pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)
    

    Or,

    pd.concat({
            k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
        }, 
        axis=0)
    

                  att_1     att_2
    12 Category 1     1  whatever
       Category 2    23   another
    15 Category 1    10       foo
       Category 2    30       bar
    

提交回复
热议问题