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

numpy ufunc 'equal'类型匹配错误解决(无需升级版本)

解决numpy 1.21.6中np.equal比较字符串数组报错的问题

问题重现

在numpy 1.21.6环境执行以下代码时触发UFuncTypeError,但numpy 1.24.2环境可正常运行:

import numpy as np

a = ["192.168.0.1", "192.168.0.2", "192.168.0.3"]
b = "192.168.0.3"

a = np.array(a, dtype=str)
b = np.array(b, dtype=str)

result = np.equal(a,b)

错误信息:

numpy.core._exceptions.UFuncTypeError: ufunc 'equal' did not contain a loop with signature matching types (dtype('<U1'), dtype('<U1')) -> dtype('bool')

原因分析

numpy 1.21.6中,直接将单个字符串传入np.array(b, dtype=str)时,会把字符串拆分为单个字符的数组(dtype='<U1');而数组a的元素是完整IP字符串(dtype='<U11'),两者类型、维度不匹配,导致np.equal无法正常执行比较。numpy 1.24.2优化了该逻辑,单个字符串转数组会保留为单个元素的数组,因此可以正常比较。

解决方案

方案1:直接使用字符串标量与数组比较

无需将b转为数组,直接用原字符串标量和数组a比较,numpy会自动处理广播逻辑:

import numpy as np

a = ["192.168.0.1", "192.168.0.2", "192.168.0.3"]
b = "192.168.0.3"

a = np.array(a, dtype=str)
result = np.equal(a, b)

方案2:将b包装为列表后转数组

把b放入列表再转为数组,确保生成单个元素的数组,与a的元素类型匹配:

import numpy as np

a = ["192.168.0.1", "192.168.0.2", "192.168.0.3"]
b = "192.168.0.3"

a = np.array(a, dtype=str)
b = np.array([b], dtype=str)  # 包装为列表后转数组,保证是单个元素的数组
result = np.equal(a, b)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:23:18