pandas 数据框.按值和计数分组
问题描述:
我有下表:
Days, Age, Sex
5, 39, F
4, 54, M
4, 26, M
5, 42, M
4, 29, M
我想分别计算F和M的行数.以下命令有效,但是我对表示形式不满意:
I want to count number of rows with F and M separately. The following command works, but I'm not OK with the representation:
df.groupby("Sex").count()
什么是最好的方法?谢谢.
What will be the best way to do it? Thank you.
答
只需添加到Wen的答案中即可.或者,可以在使用df.Sex
选择列时使用value_counts
.
Just to add to Wen's answer. Alternatively, you can use value_counts
while selecting the column with df.Sex
.
df.Sex.value_counts()
M 4
F 1
Name: Sex, dtype: int64