2

I have the following data frame like (in reality with hundreds of rows)

    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

What I want to do is to get a nested dictionary that look like that:

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

and so on. So in other words I want to determine the number of times winners won in the Outdoor and in the Indoor court.

Thank you in advance!

2 Answers 2

5

Use crosstab with DataFrame.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}}
Sign up to request clarification or add additional context in comments.

2 Comments

Also possible pd.crosstab(df['Court'], df['Winner']).to_dict() rather than using .T
You are always first!
3

You can do it with a pivot_table and 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)

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.