Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding rows to an empty 2D NumPy array

Tags:

python

numpy

I want to start with an empty 2D NumPy array, and then add some rows to it. However, so far I have only been able to do this with a 1D array. Here is what I have tried so far:

a = numpy.array([])
a = numpy.append(a, [1, 2])
a = numpy.append(a, [8, 8])
print a

The output I get is:

[1, 2, 8, 8]

Whereas I want the output to be:

[[1, 2], [8, 8]]

How can I do this?

like image 227
Karnivaurus Avatar asked Nov 21 '14 13:11

Karnivaurus


People also ask

How do I add rows to an empty NumPy array?

Numpy provides the function to append a row to an empty Numpy array using numpy. append() function.

How do you create an empty 2D NumPy array?

Create an empty 2D Numpy array using numpy.empty() To create an empty 2D Numpy array we can pass the shape of the 2D array ( i.e. row & column count) as a tuple to the empty() function. It returned an empty 2D Numpy Array of 5 rows and 3 columns but all values in this 2D numpy array were not initialized.


1 Answers

Try this:

>>> a = numpy.empty((0,2),int)
>>> a = numpy.append(a, [[1, 2]], axis=0)
>>> a = numpy.append(a, [[8, 8]], axis=0)
>>> a
array([[ 1,  2],
       [ 8,  8]])
like image 167
Riyaz Avatar answered Sep 20 '22 22:09

Riyaz