'How to count the values of multiple '0' and '1' columns and group by another binary column ('Male' and Female')?

I'd like to group the binary information by 'Gender' and count the values of the other/ following fields 'Married', 'Citizen' and 'License'

The below code was my attempt, but it was unsucessful.

dmo_df.groupby(['Gender'], as_index = True)['Married', 'Citizen','License'].apply(pd.Series.value_counts)

enter image description here

The resulting data frame/ output should look as such:

enter image description here

Sorry for the poor quality photos.



Solution 1:[1]

I think you're trying to get sum and not value_counts:

>>> df.groupby('Gender')[["Married","Citizen","License"]].sum()
        Married  Citizen  License
Gender                           
Female        3        3        0
Male          5        7        4

If you want value_count, try:

>>> df.groupby('Gender').agg({i:"value_counts" for i in ["Married", "Citizen", "License"]}).fillna(0)
          Married  Citizen  License
Gender                             
Female 0      0.0      0.0      3.0
       1      3.0      3.0      0.0
Male   0      2.0      0.0      3.0
       1      5.0      7.0      4.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1