I have a pandas dataframe.
df = pd.DataFrame({'A':['ant','ant','cherry', 'dog', 'ant'], 'B':['animal','animal', 'fruit', 'animal', 'animal'], 'C':['small','small','small', 'big', 'small']})
A B C
0 ant animal small
1 ant animal small
2 cherry fruit small
3 dog animal big
4 ant animal small
I need to do a groupby so that the result is in the following form.
A B C Count_A
0 ant animal small 3
1 cherry fruit small 1
2 dog animal big 1
I have tried the following:
s = df.groupby(['A','B','C'])['A'].count()
The result is what I needed. However, I am unable to do any slicing on it since, all columns 'A','B' and 'C' have become the index now. the method .reset_index()
also does not work. I get a value error ValueError: cannot insert A, already exists
.
Would anyone be able to help me regarding this?