python - 从 pd 数据帧 Python 创建嵌套字典

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

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

提前谢谢您!

最佳答案

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

关于python - 从 pd 数据帧 Python 创建嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60319015/

相关文章:

python - 加入并发 Python 输出

python - BeautifulSoup 将主表中的多个表分组

python - 从 DataFrame 行获取行索引

python - 执行 Pandas Groupby 和百分比增加/减少

python - 获取与关键字匹配的每个数据框单元格的内容

python - 如何将唯一的行组合转换为排序的元组

python - h2o AutoML 与 h2o XGBoost - 模型指标

python - 使用 if/else 语句创建一个新的可变数值列

python - Spyder : How to make pandas. 图(subplots =True)在关闭绘图窗口后再次显示?

python - 对数据框进行操作以将行转换为单独的列