Unsuccessful append to an empty NumPy array

前端 未结 6 1605
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 14:05

I am trying to fill an empty(not np.empty!) array with values using append but I am gettin error:

My code is as follows:

import numpy as np
result=np         


        
6条回答
  •  死守一世寂寞
    2020-12-23 15:00

    I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful:

    Initialise empty array:

    >>> a = np.zeros((0,3)) #or np.empty((0,3)) or np.array([]).reshape(0,3)
    >>> a
    array([], shape=(0, 3), dtype=float64)
    

    Now you can use this array to append rows of similar shape to it. Remember that a numpy array is immutable, so a new array is created for each iteration:

    >>> for i in range(3):
    ...     a = np.vstack([a, [i,i,i]])
    ...
    >>> a
    array([[ 0.,  0.,  0.],
           [ 1.,  1.,  1.],
           [ 2.,  2.,  2.]])
    

    np.vstack and np.hstack is the most common method for combining numpy arrays, but coming from Matlab I prefer np.r_ and np.c_:

    Concatenate 1d:

    >>> a = np.zeros(0)
    >>> for i in range(3):
    ...     a = np.r_[a, [i, i, i]]
    ...
    >>> a
    array([ 0.,  0.,  0.,  1.,  1.,  1.,  2.,  2.,  2.])
    

    Concatenate rows:

    >>> a = np.zeros((0,3))
    >>> for i in range(3):
    ...     a = np.r_[a, [[i,i,i]]]
    ...
    >>> a
    array([[ 0.,  0.,  0.],
           [ 1.,  1.,  1.],
           [ 2.,  2.,  2.]])
    

    Concatenate columns:

    >>> a = np.zeros((3,0))
    >>> for i in range(3):
    ...     a = np.c_[a, [[i],[i],[i]]]
    ...
    >>> a
    array([[ 0.,  1.,  2.],
           [ 0.,  1.,  2.],
           [ 0.,  1.,  2.]])
    

提交回复
热议问题