简体   繁体   中英

Adding a New Column/Array to a Numpy Array

I am trying to add a column to a numpy array. Each row currently has four values, I would like each row to have five values. Below is the reproducible example which returns ValueError: all the input arrays must have same number of dimensions I do not understand why I get the error because Y has the same length as X , just as b has the same length as a in the documentation . Ultimately, I would like the most efficient way to add an array like Y to an existing array like X as a new column for each row.

import numpy as np
from sklearn import datasets

#Documentation
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
c = np.concatenate((a, b.T), axis=1)
print(c)

#My Case
iris = datasets.load_iris()
X = iris.data
Y = iris.target
Z = np.concatenate((X, Y.T), axis = 1) #Is transpose necessary for single dimension array? Throws error either way
print(Z)

Edit: I should add that in practice what I will be working with is predicted values from a model fit from sklearn . So what I am particularly interested in is what the most efficient way to add the predicted values to an existing array like X, ie the format used by sklearn. This solution below is from M4rtini's comment, which I believe is equivalent to one of Dietrich's solutions. Is this the fastest implementation?

#My Case
import numpy as np
from sklearn import datasets
from sklearn.linear_model import LinearRegression

iris = datasets.load_iris()
X = iris.data
Y = iris.target
model = LinearRegression()
model.fit(X,Y)
y_hat = model.predict(X).reshape(-1,1)
Z = np.concatenate((X, y_hat), axis = 1)

Note that b is a 2D array:

In [1848]: b = np.array([[5, 6]])

In [1849]: b.shape
Out[1849]: (1, 2)

YT doesn't make Y a 2D array:

In [1856]: Y
Out[1856]: array([0, 1, 2, 3])

In [1857]: Y.T
Out[1857]: array([0, 1, 2, 3])

In [1858]: Y.T.shape
Out[1858]: (4,)

to make Y a 2D array:

In [1867]: Y1=Y.reshape(-1, 1)

In [1868]: Y1
Out[1868]: 
array([[0],
       [1],
       [2],
       [3]])

In [1869]: Y2=Y.reshape(1, -1)

In [1870]: Y2
Out[1870]: array([[0, 1, 2, 3]])

or use np.newaxis :

In [1872]: Y3
Out[1872]: 
array([[0],
       [1],
       [2],
       [3]])

In [1873]: Y4=Y[np.newaxis, :]

In [1874]: Y4
Out[1874]: array([[0, 1, 2, 3]])

To make sure your dimensions match, try:

Z = np.vstack((X.T,Y)).T

or

Yr = np.reshape(Y, (len(Y),1))
Z = np.hstack((X,Yr))

because

X.shape  = (150, 4)
Y.shape  = (150,)
Yr.shape = (150,1)
Z.shape  = (150,5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM