Reputation: 1439
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?
Upvotes: 1
Views: 227
Reputation: 231335
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)
Upvotes: 3
Reputation: 221504
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]])))
Upvotes: 0
Reputation: 1439
Numpy requires double brackets to declare an array literal, so
np.array([1,2])
needs to be
np.array([[1,2]])
Upvotes: 0