1

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.

4
  • Just use np.column_stack. Commented Sep 6, 2017 at 2:56
  • Did you try to adapt my answer to your previous question? np.insert(feature_matrix,0,[10,20,30],ax‌​is=1); stackoverflow.com/questions/46065339/… Commented Sep 6, 2017 at 3:02
  • Yes, I get SyntaxError: invalid character in identifier. that comes for axis part. Commented Sep 6, 2017 at 3:05
  • Possible duplicate of How to add an extra column to an numpy array Commented Sep 6, 2017 at 7:15

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.