[SOLVED] Python – how to add another "column" to numpy ndarray

Issue

I have a 34000,18 dimension numpy array and I have a 34000,1 array that needs to be appended to the first one at the end.

X_train.shape
=(34189, 18)

type(X_train)
= numpy.ndarray

y_train.shape
= (34189,)

my attempt:

Data = np.append(X_train,y_train)
and now its returning a (649591,) np array.

Any help please?

Additionally, how would I take a column out of the numpy.ndarray?
I.e after I have put them together and I have sorted my data- how would i then proceed to take the (34189,19) dimension array and turn it into two arrays being – (34189, 18) and (34189, 1)? (reversing what I am asking above)

Thank you

Solution

An array with ndim == 1 is implicitly a row, not a column. The simplest way would be to turn it into a column and use np.concatenate:

np.concatenate((X_train, Y_train[:, None]), axis=1)

You could do the same with np.append:

np.append(X_train, Y_train[:, None], axis=1)

Other ways to turn Y_train into a column include Y_train.reshape(-1, 1) and np.atleast_2d(Y_train).

Answered By – Mad Physicist

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *