Pandas 中使用 groupby 和向量平均值的前所未有的 TypeError

Unprecedented TypeError using groupby and mean of vectors in Pandas

这是一个示例数据框:

df = pd.DataFrame({'Cat' : ['a', 'a', 'b'], 'Vec' : [[1, 2, 3], [4, 5, 6], [1, 2, 3]]})

print (df)
  Cat        Vec
0   a  [1, 2, 3]
1   a  [4, 5, 6]
2   b  [1, 2, 3]

我的目标是分组 Cat 并沿第 0 轴取这些向量的平均值:

                 Vec
Cat                 
a    [2.5, 3.5, 4.5]
b    [1.0, 2.0, 3.0]

第一个明显的解决方案似乎是:

df.groupby('Cat').Vec.apply(np.mean)

但这给了我:

TypeError: Could not convert [1, 2, 3, 4, 5, 6] to numeric

但是,这有效:

df.groupby('Cat').Vec.apply(lambda x: np.mean(x.tolist(), axis=0))

此外,同样的技术在这个答案中效果很好:

好像有点迂回。为什么第一种方法会出现错误,我该如何解决?

df = pd.DataFrame({
    'Cat': ['a', 'a', 'b'],
    'Vec': [np.array([1, 2, 3]), np.array([4, 5, 6]), np.array([1, 2, 3])]
})


df.groupby('Cat').Vec.apply(np.mean)

Cat
a    [2.5, 3.5, 4.5]
b    [1.0, 2.0, 3.0]
Name: Vec, dtype: object

df = pd.DataFrame({
    'Cat': ['a', 'a', 'b'],
    'Vec': [[1, 2, 3], [4, 5, 6], [1, 2, 3]]
})

df.Vec.apply(np.array).groupby(df.Cat).apply(np.mean)

Cat
a    [2.5, 3.5, 4.5]
b    [1.0, 2.0, 3.0]
Name: Vec, dtype: object

问题是 np.mean 可以获取列表列表,但不能获取列表数组。

查看这些示例

np.mean(df.loc[df.Cat.eq('a'), 'Vec'].values, 0)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-380-279352aca85f> in <module>()
----> 1 np.mean(df.loc[df.Cat.eq('a'), 'Vec'].values, 0)

//anaconda/envs/3.6/lib/python3.6/site-packages/numpy/core/fromnumeric.py in mean(a, axis, dtype, out, keepdims)
   2907 
   2908     return _methods._mean(a, axis=axis, dtype=dtype,
-> 2909                           out=out, **kwargs)
   2910 
   2911 

//anaconda/envs/3.6/lib/python3.6/site-packages/numpy/core/_methods.py in _mean(a, axis, dtype, out, keepdims)
     80             ret = ret.dtype.type(ret / rcount)
     81     else:
---> 82         ret = ret / rcount
     83 
     84     return ret

TypeError: unsupported operand type(s) for /: 'list' and 'int'

np.mean(df.loc[df.Cat.eq('a'), 'Vec'].values.tolist(), 0)

array([ 2.5,  3.5,  4.5])