Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating numpy vector and matrix horizontally

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)
like image 737
pdubois Avatar asked Oct 29 '15 02:10

pdubois


People also ask

How do I horizontally concatenate in NumPy?

hstack() function. The hstack() function is used to stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.

How do you stack two arrays horizontally in Python?

hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array. Parameters : tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the second axis.

How do I concatenate a NumPy array vertically?

NumPy: vstack() function The vstack() function is used to stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). The arrays must have the same shape along all but the first axis.

Can you concatenate NumPy arrays?

Join a sequence of arrays along an existing axis. The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). The axis along which the arrays will be joined.


2 Answers

>>> 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.

like image 81
mtrw Avatar answered Sep 25 '22 22:09

mtrw


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]
like image 35
Hooting Avatar answered Sep 24 '22 22:09

Hooting