user8566323
user8566323

Reputation:

Add an extra column to ndarray in python

I have a ndarray as follows.

feature_matrix = [[0.1, 0.3], [0.7, 0.8], [0.8, 0.8]]

I have a position ndarray as follows.

position = [10, 20, 30]

Now I want to add the position value at the beginning of the feature_matrix as follows.

[[10, 0.1, 0.3], [20, 0.7, 0.8], [30, 0.8, 0.8]]

I tried the answers in this: How to add an extra column to an numpy array

E.g.,

feature_matrix = np.concatenate((feature_matrix, position), axis=1)

However, I get the error saying that;

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

Please help me to resolve this prblem.

Upvotes: 1

Views: 3699

Answers (2)

ThomasGuenet
ThomasGuenet

Reputation: 183

It is the shape of the position array which is incorrect regarding the shape of the feature_matrix.

>>> feature_matrix
array([[ 0.1,  0.3],
       [ 0.7,  0.8],
       [ 0.8,  0.8]])

>>> position 
array([10, 20, 30])

>>> position.reshape((3,1))
array([[10],
       [20],
       [30]])

The solution is (with np.concatenate):

>>> np.concatenate((position.reshape((3,1)), feature_matrix), axis=1)
array([[ 10. ,   0.1,   0.3],
       [ 20. ,   0.7,   0.8],
       [ 30. ,   0.8,   0.8]])

But np.column_stack is clearly great in your case !

Upvotes: 0

user8566323
user8566323

Reputation:

This solved my problem. I used np.column_stack.

feature_matrix = [[0.1, 0.3], [0.7, 0.8], [0.8, 0.8]]
position = [10, 20, 30]
feature_matrix = np.column_stack((position, feature_matrix))

Upvotes: 2

Related Questions