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.

  • Just use `np.column_stack`. – Divakar Sep 06 '17 at 02:56
  • Did you try to adapt my answer to your previous question? `np.insert(feature_matrix,0,[10,20,30],ax‌​is=1)`; https://stackoverflow.com/questions/46065339/how-to-insert-list-of-ndarray-lists-to-a-newndarray-in-python – hpaulj Sep 06 '17 at 03:02
  • Yes, I get SyntaxError: invalid character in identifier. that comes for axis part. –  Sep 06 '17 at 03:05
  • Possible duplicate of [How to add an extra column to an numpy array](https://stackoverflow.com/questions/8486294/how-to-add-an-extra-column-to-an-numpy-array) – Wilmar van Ommeren Sep 06 '17 at 07:15

2 Answers2

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))
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 !

ThomasGuenet
  • 183
  • 1
  • 7
  • 17