gpt4 book ai didi

python - Numpy:如何添加两个从不同类型转换而来的 np?

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:17 25 4
gpt4 key购买 nike

我有两个不同类型的数组。

>>> type(pred)
<type 'numpy.ndarray'>
>>> type(label1)
<type 'tuple'>

将它们转换成 np.ndarray

>>> nl = np.array(label1)
>>> npred = np.array(pred)
>>> type(nl)
<type 'numpy.ndarray'>
>>> type(npred)
<type 'numpy.ndarray'>
>>> nl.shape
(189,)
>>> npred.shape
(189,)

可以看到,nlnpred 这两个变量实际上是相同的类型和维度。

但是,当我尝试减去它们时,发生了错误。

>>> nl - npred
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'numpy.ndarray'

这很奇怪,不是吗?

最佳答案

您遇到的问题是,虽然 nlnprednumpy.ndarray 对象,但它们可以包含异构数据。见文件 numpy.dtype :

A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types.

因此,如果 n1 是一个字符串数组,而 npred 是一个整数数组,则您无法执行添加操作:

>>> import numpy as np
>>> a = np.array(['a', 'b', 'c'])
>>> b = np.array([1, 2, 3])
>>> type(a), type(b)
(numpy.ndarray, numpy.ndarray)
>>> a + b
unsupported operand type(s) for +: 'numpy.ndarray' and 'numpy.ndarray

如果您想知道数组的内容类型:

>>> a.dtype, b.dtype
(dtype('S1'), dtype('int64'))

因此,您必须知道每个数组包含哪种数据类型。这不是尺寸问题。

关于python - Numpy:如何添加两个从不同类型转换而来的 np?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19956189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com