numpy array: IndexError: too many indices for array

前端 未结 3 2011
盖世英雄少女心
盖世英雄少女心 2021-01-04 17:47

This works:

>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> a[: , 2]
array([ 3,  7, 11])

This doesn\'t

3条回答
  •  无人及你
    2021-01-04 18:32

    The first array has shape (3,4) and the second has shape (3,). The second array is missing a second dimension. np.array is unable to use this input to construct a matrix (or array of similarly-lengthed arrays). It is only able to make an array of lists.

    >>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
    
    >>> print(a)
    [[ 1  2  3  4]
     [ 5  6  7  8]
     [ 9 10 11 12]]
    
    >>> print(type(a))
    
    
    
    >>> b = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])
    
    >>> print(b)
    [list([1, 2, 3, 4]) list([5, 6, 7, 8]) list([9, 10, 11])]
    
    >>> print(type(b))
    
    

    So they are both Numpy arrays, but only the first can be treated as a matrix with two dimensions.

提交回复
热议问题