python - 具有值计数的熊猫 groupby
问题描述
我有一个熊猫数据框。
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
我需要做一个 groupby 以便结果如下所示。
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
。
有人能帮我解决这个问题吗?