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

为何np.vectorize会将一维数组的np.uint8元素转为int,却保留列表元素类型?

关于np.vectorize处理numpy元素类型差异的疑问

测试函数定义

我定义了如下Python函数:

import numpy as np

def f(x):
    print(f"x is {x} and has type {type(x)}")
    try:
        print(f"x.dtype is {x.dtype}")
    except AttributeError:
        print("no dtype exists on x")
    return x

该函数接收一个值,输出其类型及是否存在.dtype属性,随后返回该值。

不同调用场景的现象

场景1:输入为numpy一维数组

用np.vectorize包装函数后传入numpy数组调用:

res = np.vectorize(f)(np.array([np.uint8(1)])) # res will be: array([1], dtype=uint8)

调用后输出:

x is 1 and has type <class 'numpy.uint8'>
x.dtype is uint8
x is 1 and has type <class 'int'>
no dtype exists on x

我理解前两行输出:np.vectorize在实际遍历输入数组元素前,会取第一个元素运行函数以确定输出类型和大小。但后续遍历元素时,原numpy.uint8元素被转为了Python int类型,这让我感到困惑。

场景2:输入为列表或单个numpy标量

当输入为包含np.uint8(1)的列表,或是单个np.uint8(1)时:

res = np.vectorize(f)([np.uint8(1)]) # res: array([1], dtype=uint8)
res = np.vectorize(f)(np.uint8(1)) # res: array(1, dtype=uint8)

两次调用均输出:

x is 1 and has type <class 'numpy.uint8'>
x.dtype is uint8
x is 1 and has type <class 'numpy.uint8'>
x.dtype is uint8

疑问

为何np.vectorize处理一维数组的np.uint8元素时会将其转为int,却保留列表元素的类型不变?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 13:27:33