当应用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

提前谢谢您!

推荐答案

np.sum返回每个组的唯一元素(其总和),而np.unique返回array.当返回非对象数组时,会进行内部判断以返回此错误.

您可以转换为List以避免此问题:

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

Python相关问答推荐

在Python中对分层父/子列表进行排序

在内部列表上滚动窗口

如何在msgraph.GraphServiceClient上进行身份验证?

如何在箱形图中添加绘制线的传奇?

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

如何避免Chained when/then分配中的Mypy不兼容类型警告?

发生异常:TclMessage命令名称无效.!listbox"

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

两个pandas的平均值按元素的结果串接元素.为什么?

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

如何在FastAPI中为我上传的json文件提供索引ID?

Python避免mypy在相互引用中从另一个类重定义类时失败

比Pandas 更好的 Select

在numpy数组中寻找楼梯状 struct

为什么t sns.barplot图例不显示所有值?'

如何合并具有相同元素的 torch 矩阵的行?

什么是一种快速而优雅的方式来转换一个包含一串重复的列,而不对同一个值多次运行转换,

.awk文件可以使用子进程执行吗?

多个布尔条件的`jax.lax.cond`等效项

生产者/消费者-Queue.get by list