Reputation: 2649
I am trying to find count of values in column C
based on columns A
and B
. I was trying groupby with no success. How can I achieve this?
df = DataFrame({'A' : ['foo', 'foo', 'foo', 'foo',
'bar', 'bar', 'bar', 'bar'],
'B' : ['1', '1', '1', '2',
'1', '1', '2', '2'],
'C' : [2, 2, 3, 3, 2, 1, 2, 1]})
Result
A, B, C, Count
foo, 1, 2, 2
foo, 1, 3, 1
foo, 2, 3, 1
bar, 1, 1, 1
bar, 1, 2, 1
bar, 2, 1, 1
bar, 2, 2, 1
Upvotes: 1
Views: 2105
Reputation: 7822
Is this what you're looking for?
In [44]: table = pd.pivot_table(df, values='C', index='A',columns='B', aggfunc=len)
In [45]: df
Out[45]:
A B C
0 foo 1 2
1 foo 1 3
2 foo 1 3
3 foo 2 3
4 bar 1 2
5 bar 1 3
6 bar 2 2
7 bar 2 2
In [46]: table
Out[46]:
B 1 2
A
bar 2 2
foo 3 1
Upvotes: 1