Concatenating numpy vector and matrix horizontally

Question:

I have the following numpy vector m and matrix n

import numpy as np
m = np.array([360., 130., 1.])
n = np.array([[60., 90., 120.], 
              [30., 120., 90.],
              [1.,  1.,   1. ]])

What I want to do is to concatenate them horizontally resulting in

np.array([[60., 90., 120.,360.], 
          [30., 120., 90., 130.],
          [1.,  1.,   1., 1. ]])

What’s the way to do it?

I tried this but failed:

np.concatenate(n,m.T,axis=1)
Asked By: pdubois

||

Answers:

one way to achieve the target is by converting m to a list of list

import numpy as np
m = np.array([360., 130., 1.])
n = np.array([[60., 90., 120.],
              [30., 120., 90.],
              [1.,  1.,   1. ]])
m = [[x] for x in m]
print np.append(n, m, axis=1)

Another way is to use np.c_,

import numpy as np
m = np.array([360., 130., 1.])
n = np.array([[60., 90., 120.],
              [30., 120., 90.],
              [1.,  1.,   1. ]])
print np.c_[n,m]
Answered By: Hooting
>>> np.hstack((n,np.array([m]).T))
array([[  60.,   90.,  120.,  360.],
       [  30.,  120.,   90.,  130.],
       [   1.,    1.,    1.,    1.]])

The issue is that since m has only one dimension, its transpose is still the same. You need to make it have shape (1,3) instead of (3,) before you take the transpose.

A much better way to do this is np.hstack((n,m[:,None])) as suggested by DSM in the comments.

Answered By: mtrw

I would simply do np.column_stack((n, m)).

Answered By: Tobia Marcucci
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.