You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

np.maximum.reduce处理含int与Pandas Series列表时行为异常报错

当列表中的元素混合了标量数字(如int类型)和数组/Pandas Series对象时,np.maximum.reduce(lst) 的行为既与 functools.reduce(np.maximum, lst) 存在差异,也和 np.maximum 本身的预期行为不一致。

np.maximum.reduce 运行表现

执行如下代码:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': [1, 3, 2]})

np.maximum.reduce([df['a'], 2])

代码最后一行会抛出如下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

直接调用 np.maximum 运行表现

执行如下代码:

np.maximum(df['a'], 2)

可得到符合预期的逐元素计算结果:

0    2
1    3
2    2
Name: a, dtype: int64

reduce(np.maximum) 运行表现

执行如下代码:

reduce(np.maximum, [df['a'], 2])

同样可得到符合预期的计算结果:

0    2
1    3
2    2
Name: a, dtype: int64

测试使用的版本信息

  • pandas 版本:1.2.5
  • numpy 版本:1.19.5
  • python 版本:3.7.9

内容的提问来源于stack exchange,提问作者Tim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 00:51:16