ValueError: 必须在pandas中生成聚合值

1 投票
1 回答
28 浏览
提问于 2025-04-14 17:51

我在使用np.sum的时候遇到了一个ValueError,我需要计算聚合值。有没有什么建议可以解决这个问题?顺便说一下,这个逻辑之前是可以正常运行的。

df1 = 
self_id  |  id  |  rating  |          comment            |
1          820     (blank)            (blank)   
2          823     strong      good performance
3          826     weak               (blank)

#Pivoting the NaNs/unique values
ndf1 = pd.pivot_table(data=df1, index=['self_id'], 
                     aggfunc={'id':np.unique, 
                              'Ratings':np.sum, 
                              'Comments':np.sum})
ValueError: Must produce aggregated value

提前谢谢你们!

1 个回答

1

np.sum 会对每一组数据进行求和,返回每组的总和,也就是一个独特的结果。而 np.unique 则是返回一个数组,里面包含了所有不同的元素。如果返回的不是对象数组,系统会进行内部检查并返回错误。

为了避免这个问题,你可以把数据转换成列表:

ndf1 = pd.pivot_table(data=df1, index=['self_id'], 
                     aggfunc={'id':lambda x: np.unique(x).tolist(), 
                              'rating':np.sum, 
                              'comment':np.sum})

输出结果:

                  comment     id  rating
self_id                                 
1                       0  [820]       0
2        good performance  [823]  strong
3                       0  [826]    weak

撰写回答