I'm trying to append a numpy array to another array. I have 3 arrays with a shape of (3, )
. I want to get a shape of (3, 3)
, but I get (9, )
in output.
data = []
for i in range(3) :
data = np.append(data, next[i], axis=0)
print(data.shape, data)
output :
(9,)
['John' 'Andrew' 'Mike' 4 23 45 123.0 31.3 344.0]
the output I want should have shape (3, 3)
like this :
(3,3)
['John' 'Andrew' 'Mike' ,
4 23 45 ,
123.0 31.3 344.0]
CodePudding user response:
Check one step:
In [6]: np.append([], [1,2,3], axis=0)
Out[6]: array([1., 2., 3.])
np.array([])
is a (0,) shape array; join that with a (3,) shape on axis 0 (the only possible one), and you get a (3,) shape. Join that (3,) with another (3,), again on axis 0, you get (6,). Not the (2,3) that you seem to imagine.
Too many new users seem to think that np.array([])
is a clone of the []
list, and np.append
is a clone of the list append. Stick with list append if you don't understand array concatenate
and array dimensions.
CodePudding user response:
I am assuming next is a 2D list in your case. Please avoid using this as a variable name since it is a keyword in python.
If next is a 2D list of 3x3, then you can simply use asmatrix in numpy:
data = np.asmatrix(next)
print(data.shape, data)
Alternatively, you can use vstack:
data = np.array(next[0])
for i in range(1,3) :
data = np.vstack((data,next[i]))
print(data.shape, data)