1

I have initialized this empty 2d np.array

inputs = np.empty((300, 2), int)

And I am attempting to append a 2d row to it as such

inputs = np.append(inputs, np.array([1,2]), axis=0)

But Im getting

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

And Numpy thinks it's a 2 row 0 dimensional object (transpose of 2d)

np.array([1, 2]).shape

(2,)

Where have I gone wrong?

2
  • Notice the shape of your inserted array when you do: np.array([[1, 2]]).shape Commented Sep 7, 2016 at 4:26
  • (2,) is a 1d array. It's not a transpose of anything else. Commented Sep 7, 2016 at 5:42

3 Answers 3

3

To add a row to a (300,2) shape array, you need a (1,2) shape array. Note the matching 2nd dimension.

np.array([[1,2]]) works. So does np.array([1,2])[None, :] and np.atleast_2d([1,2]).

I encourage the use of np.concatenate. It forces you to think more carefully about the dimensions.

Do you really want to start with np.empty? Look at its values. They are random, and probably large.

@Divakar suggests np.row_stack. That puzzled me a bit, until I checked and found that it is just another name for np.vstack. That function passes all inputs through np.atleast_2d before doing np.concatenate. So ultimately the same solution - turn the (2,) array into a (1,2)

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

Comments

0

Numpy requires double brackets to declare an array literal, so

np.array([1,2])

needs to be

np.array([[1,2]])

2 Comments

Both create arrays, one has shape (2,), the other (1,2), 1d and 2d. I don't know what you mean by array literal.
@hpaulj: I would hazard that redress is trying to say "to literally translate the matlab array literal [1, 2] into a numpy, you [sometimes] need an extra set of brackets"
0

If you intend to append that as the last row into inputs, you can just simply use np.row_stack -

np.row_stack((inputs,np.array([1,2])))

Please note this np.array([1,2]) is a 1D array.

You can even pass it a 2D row version for the same result -

np.row_stack((inputs,np.array([[1,2]])))

2 Comments

Never heard of row_stack before! vstack yes. :)
@hpaulj Yeah, apparently, its not even documented :)

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.