descriptive stats for two categorical variables (pandas)

Viewed 2479

I need to get the mean and median for frequencies between two categorical variables. E.g.:

Label Letter Num
Foo | A | 1
Foo | B | 2
Foo | C | 4
Bar | A | 2
Bar | G | 3
Bar | N | 1
Bar | P | 2
Cee | B | 1
Cee | B | 2
Cee | C | 4
Cee | D | 5

For instance, what's the mean and median number of letters per label. Here there are 11 cases out of three possible labels (M=3.667) and the median is 4 (3 foo, 4 bar, 4 cee). How can I calculate this in pandas. Is it possible to do this with a groupby statement? My data set is much larger than this.

1 Answers

Need value_counts for one column or groupby + size (or count if need omit NaNs):

a = df['Label'].value_counts()
print (a)
Cee    4
Bar    4
Foo    3
Name: Label, dtype: int64

#alternative
#a = df.groupby('Label').size()
print (a.mean())
3.6666666666666665

print (a.median())
4.0

a = df.groupby(['Label','Letter']).size()
print (a)
Label  Letter
Bar    A         1
       G         1
       N         1
       P         1
Cee    B         2
       C         1
       D         1
Foo    A         1
       B         1
       C         1
dtype: int64

print (a.mean())
1.1

print (a.median())
1.0
Related