gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:13:34 26 4
gpt4 key购买 nike

这是一个示例数据框:

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

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

最佳答案

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

关于python - 在 Pandas 中使用 groupby 和向量平均值的前所未有的 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45726683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com