将嵌套字典解压缩到pandas DataFrame

时间:2019-02-04 18:06:16

标签: python pandas dataframe dictionary

我的字典当前是通过以下方式设置的:

{'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()参数必须有所不同。

2 个答案:

答案 0 :(得分:1)

一种方法是结合使用stackunstack

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

答案 1 :(得分:0)

您可以将pd.concat与生成器表达式一起使用。假设输入字典dct,并且您的列表(对于任何给定的Code)都具有相同的长度。

df = pd.concat((pd.DataFrame({**{'Code': key}, **value}) \
                for key, value in dct.items()), ignore_index=True)

print(df)

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