从pd数据框Python创建嵌套字典

时间:2020-02-20 11:33:40

标签: python pandas dataframe dictionary

我有以下数据框,例如(实际上有数百行)

    Location Date       Court    Winner 
0   Paris    10/2/2018  Outdoor  Flavio
1   Paris    10/2/2018  Indoor   Luca
2   Paris    10/2/2018  Indoor   Giovanni
3   Paris    10/2/2018  Indoor   Luca

我想要做的是获得一个看起来像这样的嵌套字典:

{ 'Flavio' : { 'Outdoor' : 1 , 'Indoor' : 0 } , 'Luca' : {'Outdoor' : 0 , 'Indoor' : 2} } 

,依此类推。因此,换句话说,我想确定获胜者在室外和室内法庭获胜的次数。

提前谢谢!

2 个答案:

答案 0 :(得分:5)

crosstabDataFrame.to_dict一起使用:

d = pd.crosstab(df['Court'],df['Winner']).to_dict()
print (d)
{'Flavio': {'Indoor': 0, 'Outdoor': 1},
 'Giovanni': {'Indoor': 1, 'Outdoor': 0}, 
 'Luca': {'Indoor': 2, 'Outdoor': 0}}

答案 1 :(得分:3)

您可以使用IList<AnotherClass>pivot_table来做到这一点:

to_dict

输出:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Location':['France','France','France','France'],
                   'Court':['Outdoor','Indoor','Indoor','Indoor'],
                   'Winner':['Flavio','Luca','Giovanni','Luca']})
df = pd.pivot_table(df,values='Location',columns='Winner',index='Court',aggfunc='count',fill_value=0)
a = df.to_dict()
print(a)
相关问题