【问题标题】:Create a nested dictionary from pd dataframe Python从 pd 数据框 Python 创建嵌套字典
【发布时间】:2020-06-04 17:23:04
【问题描述】:

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

    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} } 

等等。所以换句话说,我想确定获胜者在室外和室内球场上获胜的次数。

提前谢谢你!

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    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}}
    

    【讨论】:

    • 也可以pd.crosstab(df['Court'], df['Winner']).to_dict()而不是使用.T
    • 你永远是第一!
    【解决方案2】:

    您可以使用pivot_tableto_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)
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2022-01-13
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 2019-05-22
      • 2019-01-11
      相关资源
      最近更新 更多