【问题标题】:Unprecedented TypeError using groupby and mean of vectors in PandasPandas 中使用 groupby 和向量均值的前所未有的 TypeError
【发布时间】:2017-08-17 04:39:15
【问题描述】:

这是一个示例数据框:

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))

此外,同样的技术在这个答案中效果很好:https://stackoverflow.com/a/45726608/4909087

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

【问题讨论】:

  • 这很有趣。看起来我们需要一个 ndarray 或简单的值来像这样应用np.mean,请参阅源代码中的here。不过不太确定什么是 atm 解决方案。
  • @Mitch 有趣的是,您应该对此做出回应。这个问题的灵感来自您写的最后一个答案。我尝试了与您的答案非常相似的方法,但出现了此错误,因此正在寻找替代解决方案。但是当我看到你发布这个效果很好的解决方案时,我很困惑。
  • 哈哈是的,我想通了!现在玩弄它。
  • @CoryMadden 我在输入下方包含了一个示例输出。
  • 从根本上说,numpy 和扩展的 pandas 并不是真正为处理列表数组而设计的。

标签: python pandas dataframe group-by pandas-groupby


【解决方案1】:
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])

【讨论】:

  • 这很有趣。为什么除非类型以np.array开头,否则它不起作用?
  • @cᴏʟᴅsᴘᴇᴇᴅ 查看我上面链接的源代码行 - 可以处理 ndarray,但不能处理 Python 列表。
  • @Mitch 我怀疑如果没有进行检查,传递列表应该可以工作,因为 numpy 可以处理它们。你说什么?
  • @cᴏʟᴅsᴘᴇᴇᴅ 是的,确实,仍在尝试断言 为什么 我们输入该检查:)
  • 感谢大家的帮助。
猜你喜欢
  • 2019-11-09
  • 2018-10-02
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
相关资源
最近更新 更多