有多个 "groupby" 变量和类别的麻烦(分箱数据)

Having Trouble with multiple "groupby" with a variable and a category (binned data)

df.dtypes

Close       float64
eqId          int64
date         object
IntDate       int64
expiry        int64
delta         int64
ivMid       float64
conf        float64
Skew        float64
psc         float64
vol_B      category
dtype: object

gb = df.groupby([df['vol_B'],df['expiry']])

gb.describe()

我收到一条很长的错误消息,最后一行是

AttributeError: 'Categorical' object has no attribute 'flags'

当我分别对它们中的每一个执行 groupby 时,它们各自(独立地)工作得很好,我只是无法执行多个 groupby 其中一个变量是 "bin."

此外,当我使用其他 2 个变量时,我能够执行多个 groupby &ndash 我成功地执行了这个:

gb = df.groupby([df['delta'],df['expiry']])

我遇到了与 OP 类似的问题,并在寻找解决方案时发现了这个问题。在完成 pandas documentation for categorical variables 之后对我有用的一个简单技巧是在分组之前更改分类变量的类型。

由于 vol_B 是您案例中的分类变量,您应该尝试以下操作

#Depending on the content of vol_B you can do astype(int) or astype(float) as well.
gb = df.groupby([df['vol_B'].astype(str), df['expiry']])

我还没有详细说明为什么这个行得通,那个行不通,但如果我深入了解,我会更新答案。