首页 > 解决方案 > 将嵌套字典解包到 pandas DataFrame

问题描述

我的字典目前是这样设置的:

{'0001': {'Batting Hours': [79, 154, 50, 172],
  'Bowling Hours': [101, 82, 298],
  'Date': ['02/02/2019', '02/01/2019', '02/04/2019', '02/03/2019']},
 '0002': {'Batting Hours': [7, 23, 40],
  'Bowling Hours': [14, 30, 43],
  'Date': ['02/04/2019', '02/01/2019', '02/02/2019']}}

我如何解开这个字典,以便数据框有这样的输出:

Code        Date              Batting Hours     Bowling Hours 
0001        02/02/2019                79                   101            
0001        02/01/2019                154                   82 

我尝试查看有关其他类似数据结构如何展开的文档,但我似乎无法理解。

我目前正在将这些值附加到这样的列表中

player_agg_hours_dict[Player]['Batting Hours'].append(aggregate_batting_hours)

我正在尝试输出到这样的数据框:

output_df = pd.DataFrame.from_dict(player_agg_hours_dict, orient='index').transpose() # convert dict to dataframe

而且我知道from_dict()参数必须有所不同。

标签: pythonpandasdataframedictionary

解决方案


一种方法是使用stack和的组合unstack

v = pd.DataFrame(dct).stack()

(pd.DataFrame(v.tolist(), index=v.index)
   .stack()
   .unstack(0)
   .reset_index(level=1, drop=True)
   .rename_axis('Code')
   .reset_index())

   Code Batting Hours Bowling Hours        Date
0  0001            79           101  02/02/2019
1  0001           154            82  02/01/2019
2  0001            50           298  02/04/2019
3  0001           172           NaN  02/03/2019
4  0002             7            14  02/04/2019
5  0002            23            30  02/01/2019
6  0002            40            43  02/02/2019

您也可以从以下步骤开始concat

(pd.concat({k: pd.DataFrame.from_dict(v, orient='index') for k,v in dct.items()})
   .stack()
   .unstack(1)
   .reset_index(level=1, drop=True)
   .rename_axis('Code')
   .reset_index())

   Code        Date Batting Hours Bowling Hours
0  0001  02/02/2019            79           101
1  0001  02/01/2019           154            82
2  0001  02/04/2019            50           298
3  0001  02/03/2019           172           NaN
4  0002  02/04/2019             7            14
5  0002  02/01/2019            23            30
6  0002  02/02/2019            40            43

推荐阅读