为何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
相关产品推荐
相关产品推荐

