首页 文章

numpy数组TypeError:只能将整数标量数组转换为标量索引

提问于
浏览
20
i=np.arange(1,4,dtype=np.int)
a=np.arange(9).reshape(3,3)

a
>>>array([[0, 1, 2],
          [3, 4, 5],
          [6, 7, 8]])
a[:,0:1]
>>>array([[0],
          [3],
          [6]])
a[:,0:2]
>>>array([[0, 1],
          [3, 4],
          [6, 7]])
a[:,0:3]
>>>array([[0, 1, 2],
          [3, 4, 5],
          [6, 7, 8]])

现在我想对数组进行矢量化以将它们一起打印出来 . 我试试

a[:,0:i]

要么

a[:,0:i[:,None]]

它给出了TypeError:只有整数标量数组才能转换为标量索引

4 回答

  • 0

    简短回答:

    [a[:,:j] for j in i]
    

    你要做的不是一个可矢量化的操作 . Wikipedia defines vectorization作为单个数组上的批处理操作,而不是单个标量:

    在计算机科学中,数组编程语言(也称为向量或多维语言)概括了对标量的操作,以透明地应用于向量,矩阵和高维数组 . ......在整个数组上运行的操作可以称为矢量化操作......

    在CPU级优化方面,definition of vectorization是:

    “矢量化”(简化)是重写循环的过程,因此它不是处理数组的单个元素N次,而是同时处理(比如说)数组的4个元素N / 4次 .

    您的案例的问题是每个单独操作的结果具有不同的形状: (3, 1)(3, 2)(3, 3) . 它们不能形成单个矢量化操作的输出,因为输出必须是一个连续的数组 . 当然,它可以在其中包含 (3, 1)(3, 2)(3, 3) 数组(作为视图),但这就是原始数组 a 已经执行的操作 .

    你真正想要的只是一个计算所有这些的表达式:

    [a[:,:j] for j in i]
    

    ...但它是一个简单的旧 for 循环,逐个计算每个项目 .

  • 0

    尝试以下操作将阵列更改为1D

    a.reshape((1, -1))
    
  • 5

    这可能与此特定问题无关,但我遇到了类似的问题,我在Python列表上使用了NumPy索引并得到了相同的确切错误消息:

    # incorrect
    weights = list(range(1, 129)) + list(range(128, 0, -1))
    mapped_image = weights[image[:, :, band] # image.shape = [800, 600, 3]
    # TypeError: only integer scalar arrays can be converted to a scalar index
    

    事实证明,在应用多维NumPy索引之前,我需要将一个1D Python列表的 weights 转换为NumPy数组 . 以下代码有效:

    # correct
    weights = np.array(list(range(1, 129)) + list(range(128, 0, -1)))
    mapped_image = weights[image[:, :, band] # image.shape = [800, 600, 3]
    
  • 13

    您可以使用numpy.ravel从n维数组返回一个展平的数组:

    >>> a
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])
    >>> a.ravel()
    array([0, 1, 2, 3, 4, 5, 6, 7, 8])
    

相关问题