eljusticiero67 eljusticiero67 - 3 months ago 10
Python Question

Value Counts of Column Slice to Contain All Possible Unique Values in Column

I have a df that looks like this:

group val
A 1
A 1
A 2
B 1
B 2
B 3


I want to get the value_counts for each group separately, but want to show all possible values for each value_count group:

> df[df['group']=='A']['val'].value_counts()

1 2
2 1
3 NaN
Name: val, dtype: int64


But it currently looks like this:

> df[df['group']=='A']['val'].value_counts()

1 2
2 1
Name: val, dtype: int64


Any one know any way I can show value_counts with all possible values represented?

Answer
In [185]: df.groupby('group')['val'].value_counts().unstack('group')
Out[185]: 
group    A    B
val            
1      2.0  1.0
2      1.0  1.0
3      NaN  1.0

In [186]: df.groupby('group')['val'].value_counts().unstack('group')['A']
Out[186]: 
val
1    2.0
2    1.0
3    NaN
Name: A, dtype: float64