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)
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.
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.
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.
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.
>>> 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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With