numpy array: IndexError: too many indices for array

前端 未结 3 2014
盖世英雄少女心
盖世英雄少女心 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:27

    Numpy ndarrays are meant for all elements to have the same length. In this case, your second array doesn't contain lists of the same length, so it ends up being a 1-D array of lists, as opposed to a "proper" 2-D array.

    From the Numpy docs on N-dimensional arrays:

    An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size.

    a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
    a.shape # (3,4)
    a.ndim # 2
    
    b = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])
    b.shape # (3,)
    b.ndim # 1
    

    This discussion may be useful.

提交回复
热议问题