SebMa
SebMa

Reputation: 4709

Numpy : Add a 1d array (row) to an empty 2d array in Numpy Python

I don't know the number of rows and columns of a 2d array (a) I need in advance:

a = np.empty( (0,0), dtype=np.uint8 )
a.ndim
2

I managed to convert each line I read from a file to an 1d array of bytes called line

I want to add/append each line to a, so I tried :

np.vstack( (a,line) )

but I get : ValueError: all the input arrays must have same number of dimensions

And if I call a=np.append(a,line), the number of dimensions becomes 1

Can you help ?

Upvotes: 1

Views: 2765

Answers (2)

cs95
cs95

Reputation: 402263

You're on the right track with np.vstack. The only requirement is that the arrays being stacked must have the same number of columns. Take a look at this:

array = None # initialise array to None first

for ...: # now inside the loop
    line = ... # read line from somewhere and get something like [201, 81, 237, 230]

    if array is None:
        array = line
    else: 
        array = np.vstack((array, line))

In terms of performance, this is actually a little more wasteful than just creating an array at the end out of a list. This is the problem with numpy arrays - they're immutable in terms of dimensions.

Upvotes: 2

Tom Wyllie
Tom Wyllie

Reputation: 2086

Numpy arrays cannot be appended to. The easiest way for you to do what you are trying to achieve would be to use a list and call np.asarray() on it.

a = []
# Build list from file
a = np.asarray(a)

Upvotes: 1

Related Questions