Group Value Count By Column with Pandas Dataframe

冷暖自知 提交于 2021-02-04 08:24:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!