Kyle Frye
Kyle Frye

Reputation: 121

Group Value Count By Column with Pandas Dataframe

I'm not really sure how to ask this, so I apologize if this is a repeat question. I have this data frame that looks something like this:

| ID | Attend_x | Attend_y | Attend_z | | 1 | No | No | No | | 2 | No | No | Yes | | 3 | No | Yes | No | | 4 | No | Yes | Yes |

I've been trying to figure out the right combination of group_by and count to get it to look like this:

| | Yes | No | |Attend_x| 0 | 4 | |Attend_y| 2 | 2 | |Attend_z| 2 | 2 |

I'm honestly stumped. So any advice is super appreciated. Thanks!

Upvotes: 0

Views: 103

Answers (1)

BENY
BENY

Reputation: 323226

One way from value_counts

df.iloc[:,1:].apply(pd.Series.value_counts).fillna(0).T
Out[184]: 
           No  Yes
Attend_x  4.0  0.0
Attend_y  2.0  2.0
Attend_z  2.0  2.0

Or using crosstab after melt

m = df.iloc[:,1:].melt()
pd.crosstab(m.variable, m.value)

value     No  Yes
variable         
Attend_x   4    0
Attend_y   2    2
Attend_z   2    2

Upvotes: 3

Related Questions