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?

Tobias Ribizel
  • 5,331
  • 1
  • 18
  • 33
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python – RST Nov 21 '14 at 13:41

2 Answers2

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]])
Riyaz
  • 1,430
  • 2
  • 17
  • 27
0
>>> import numpy
>>> numpy.vstack(([1, 2], [8, 8]))
array([[1, 2],
       [8, 8]])
YXD
  • 31,741
  • 15
  • 75
  • 115
  • 1
    `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. – Riyaz Nov 21 '14 at 13:45
  • 1
    Both `vstack` and `append` end up using `concatenate`. They just differ in how they tweak the inputs before. – hpaulj Nov 21 '14 at 19:33