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?
Numpy provides the function to append a row to an empty Numpy array using numpy. append() function.
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.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With