John P.
John P.

Reputation: 139

getting dictionary from pandas series

I need to write a function in pandas which gets two series as arguments: one is the grades of several students, another is their gender. As a return I need to get a dictionary with keys "male" or "female" and values which are the means of the grades over gender... As an example,if

grades = pd.Series([5, 4, 3, 5, 2]) 

and

genders = pd.Series(["female", "male", "male", "female", "male"]) 

the function must return a dictionary

{'male': 3.0, 'female': 5.0}

I know that I may create a data frame with columns which are these two series and then use groupby and to_dict() but have no idea how..

Upvotes: 0

Views: 77

Answers (2)

Zero
Zero

Reputation: 76917

Use

In [96]: grades.groupby(genders).mean().to_dict()
Out[96]: {'female': 5L, 'male': 3L}

Upvotes: 1

Lambda
Lambda

Reputation: 1392

Use

grades.groupby(genders).mean().to_dict()

Upvotes: 3

Related Questions