Reputation: 147
I would like to count how many time a person shows up in a data frame.
Say our data set is-
dic = {'firstname':['John','John','John','John','John','Susan','Mike',
'Mike','Jacob','David','Jacob','David','Jacob','David','Mike'],
'lastname':['Smith','Smith','Adams','Adams','Adams','Wilson',
'Jones','Jones','White','Miller','Peterson','Miller','White',
'Miller','Jones']}
df = pd.DataFrame(dic)
print(df)
with output-
firstname lastname
0 John Smith
1 John Smith
2 John Adams
3 John Adams
4 John Adams
5 Susan Wilson
6 Mike Jones
7 Mike Jones
8 Jacob White
9 David Miller
10 Jacob Peterson
11 David Miller
12 Jacob White
13 David Miller
14 Mike Jones
I want to count how many times a person is in this data set by first and last name.
Desired output-
firstname lastname count
0 John Smith 2
1 John Adams 3
2 Susan Wilson 1
3 Mike Jones 3
4 Jacob White 2
5 David Miller 3
6 Jacob Peterson 1
Upvotes: 0
Views: 26
Reputation: 8302
Try this,
In [22]: df.groupby(['firstname', 'lastname']).size().reset_index(name='count')
Out[22]:
firstname lastname count
0 David Miller 3
1 Jacob Peterson 1
2 Jacob White 2
3 John Adams 3
4 John Smith 2
5 Mike Jones 3
6 Susan Wilson 1
Upvotes: 1