我有一个熊猫数据框。
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
我需要进行分组,以便结果采用以下形式。
A B C Count_A
0 ant animal small 3
1 cherry fruit small 1
2 dog animal big 1
我尝试了以下方法:
s = df.groupby(['A','B','C'])['A'].count()
结果就是我所需要的。但是,由于所有列“ A”,“ B”和“ C”现在都已成为索引,因此我无法对其进行任何切片。方法.reset_index()
也不起作用。我收到值错误ValueError: cannot insert A, already exists
。
有人可以帮助我吗?