Python Pandas 基于列计算行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44111307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:39:37  来源:igfitidea点击:

Python Pandas count rows based on column

python-2.7pandasdataframerowcount

提问by raja

How to get row counts based on one column in Python pandas. For example I have a data frame like this:

如何根据 Python pandas 中的一列获取行数。例如我有一个这样的数据框:

Name         NameTitle    Sex

John         Dr           m
Mona         Dr           f
Mary         Mrs          f
Tom          Mr           m
Hyman         Mr           m 
Leila        Ms           f
Soro         Ms           f 
Christi      Ms           f
Mike         Mr           m  

I need to count the number of name titles based on sex. Desired output would be like this:

我需要根据性别计算姓名标题的数量。期望的输出是这样的:

NameTitle    Sex    Count

Dr           m      1
Dr           f      1
Mrs          f      1
Mr           m      3
Ms           f      3

回答by jezrael

Use groupby+ size+ reset_index:

使用groupby+ size+ reset_index

df = df.groupby(['NameTitle','Sex'], sort=False).size().reset_index(name='Count')
print (df)
  NameTitle Sex  Count
0        Dr   m      1
1        Dr   f      1
2       Mrs   f      1
3        Mr   m      3
4        Ms   f      3