Albert X.W.
Albert X.W.

Reputation: 193

pandas dataframe, how to get average of a value over a certain index

For example, I have a dataframe like this:

Age Gender  
20   Male  
10   Male  
18   Female  
15   Male  
19   Female  
17   Female  

How can I can a DataFrame like:

Age  Gender  
15   Male  
18   Female  

The age in the new DataFrame is the average age of the old DataFrame with corresponding Gender respectively.

Upvotes: 5

Views: 22857

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

In [51]: df.groupby('Gender', as_index=False).Age.mean()
Out[51]:
   Gender  Age
0  Female   18
1    Male   15

How can I make the result DataFrame a Series with Gender as keys/index?

In [61]: s = df.groupby('Gender').Age.mean()

In [62]: s
Out[62]:
Gender
Female    18
Male      15
Name: Age, dtype: int64

In [63]: type(s)
Out[63]: pandas.core.series.Series

Upvotes: 9

Related Questions