Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsuccessful append to an empty NumPy array

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.asarray([np.asarray([]),np.asarray([])]) result[0]=np.append([result[0]],[1,2]) 

And I am getting:

ValueError: could not broadcast input array from shape (2) into shape (0) 
like image 236
Cupitor Avatar asked Oct 28 '13 23:10

Cupitor


People also ask

How do you add to an empty array in Python?

Add Elements to an Empty List. You can add elements to an empty list using the methods append() and insert() : append() adds the element to the end of the list. insert() adds the element at the particular index of the list that you choose.

Can you append to a numpy array?

Append values to the end of an array. Values are appended to a copy of this array. These values are appended to a copy of arr.

How do you declare an empty numpy array in Python?

empty() in Python. numpy. empty(shape, dtype = float, order = 'C') : Return a new array of given shape and type, with random values.


1 Answers

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.]]) 
like image 124
Simon Streicher Avatar answered Sep 24 '22 05:09

Simon Streicher