2

I am running into errors when concatenating arrays in Python:

x = np.array([])
while condition:
    % some processing 
    x = np.concatenate([x + new_x])

The error I get is:

----> 1 x = np.concatenate([x + new_x])

ValueError: operands could not be broadcast together with shapes (0) (6) 

On a side note, is this an efficient way to grow a numpy array in Python?

1
  • Given that you're copying x on every iteration, I am not sure I would necessarily call this "efficient". Commented Dec 5, 2012 at 17:55

2 Answers 2

3

Looks like you want to call

x = np.concatenate((x, new_x))

according to the docs.

Sign up to request clarification or add additional context in comments.

3 Comments

Also, for greater control, there are the functions hstack, vstack and dstack, that are worth taking a look!
@heltonbiker How do those have greater control than concatenate? I thought concatenate can do an arbitrary axis, whereas hstack, vstack, and dstack concatenate along a particular axis.
By "greater control" I meant that, say, with hstack you always will concatenate along 1-axis. So, using hstack you won't "accidentally" concatenate along the wrong axis, so you would in this sense be more "in control" of the situation. But in the end it's a matter of perspective, of course.
0

Alternatively:

x = np.append(x,new_x)

Regarding your side note, take a look here: How to extend an array in-place in Numpy?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.