问题
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!
回答1:
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
来源:https://stackoverflow.com/questions/52470712/group-value-count-by-column-with-pandas-dataframe