在有序分类列上使用groupby的行为异常 [英] Weird behaviour with groupby on ordered categorical columns
问题描述
MCVE
df = pd.DataFrame({
'Cat': ['SF', 'W', 'F', 'R64', 'SF', 'F'],
'ID': [1, 1, 1, 2, 2, 2]
})
df.Cat = pd.Categorical(
df.Cat, categories=['R64', 'SF', 'F', 'W'], ordered=True)
如您所见,我定义了有序分类 Cat
上的列。要进行验证,请进行检查;
As you can see, I've define an ordered categorical column on Cat
. To verify, check;
0 SF
1 W
2 F
3 R64
4 SF
5 F
Name: Cat, dtype: category
Categories (4, object): [R64 < SF < F < W]
我想找到最大的PER ID类别。进行 groupby
+ max
可行。
I want to find the largest category PER ID. Doing groupby
+ max
works.
df.groupby('ID').Cat.max()
ID
1 W
2 F
Name: Cat, dtype: object
但是我不希望ID成为索引,所以我指定 as_index = False
。
But I don't want ID to be the index, so I specify as_index=False
.
df.groupby('ID', as_index=False).Cat.max()
ID Cat
0 1 W
1 2 SF
糟糕!现在,按字典顺序获取最大值。谁能解释这是否是预期的行为?还是这是一个错误?
Oops! Now, the max is taken lexicographically. Can anyone explain whether this is intended behaviour? Or is this a bug?
注意,对于此问题,解决方法是 df.groupby('ID')。Cat.max() .reset_index()
。
Note, for this problem, the workaround is df.groupby('ID').Cat.max().reset_index()
.
注意,
>>> pd.__version__
'0.22.0'
推荐答案
源代码潜水显示该标志做了两项完全不同的事情。一个人简单地忽略了石斑鱼的水平和名称,它只使用带有新范围索引的值。另一个显然保留了它们。
Source diving shows the flag does two completely different things. The one simply ignores grouper levels and names, it just takes the values with a new range index. The other one clearly keeps them.
这篇关于在有序分类列上使用groupby的行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!