6

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?

1

2 Answers 2

12

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]])
Sign up to request clarification or add additional context in comments.

Comments

0
>>> import numpy
>>> numpy.vstack(([1, 2], [8, 8]))
array([[1, 2],
       [8, 8]])

2 Comments

numpy.array(([1, 2], [8, 8])) would do the same. The question is how to append rows to an initially empty array and your code doesn't address that.
Both vstack and append end up using concatenate. They just differ in how they tweak the inputs before.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.