Reputation: 43
My problem is that I've got this array:
np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
and I want to convert the elements to array like this:
np.array([[0.0], [0.0], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
So is there a loop or a numpy function that I could use to do this task?
Upvotes: 4
Views: 264
Reputation: 152795
There are several ways to achieve this with numpy functions:
np.expand_dims
- the explicit option
>>> import numpy as np
>>> a = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
>>> np.expand_dims(a, axis=1)
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
slicing with np.newaxis
(which is an alias for None
)
>>> np.array(a)[:, np.newaxis]
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
>>> np.array(a)[:, None]
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
Instead of adding an axis
manually you can also use some default ways to create a multidimensional array and then swap the axis, for example with np.transpose
but you could also use np.swapaxes
or np.reshape
:
np.array
with ndmin=2
>>> np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5], ndmin=2).T
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
np.atleast_2d
and
>>> np.atleast_2d(a).swapaxes(1, 0)
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
Upvotes: 1
Reputation: 215117
Or simply:
arr[:,None]
# array([[ 0. ],
# [ 0. ],
# [-1.2],
# [-1.2],
# [-3.4],
# [-3.4],
# [-4.5],
# [-4.5]])
Upvotes: 13
Reputation: 140836
Isn't this just a reshape
operation from row to column vector?
In [1]: import numpy as np
In [2]: x = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
In [3]: np.reshape(x, (-1,1))
Out[3]:
array([[ 0. ],
[ 0. ],
[-1.2],
[-1.2],
[-3.4],
[-3.4],
[-4.5],
[-4.5]])
Upvotes: 6
Reputation: 4862
You can use a list comprehension:
>>> a1 = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
>>> np.array([[x] for x in a1])
array([[ 0. ],
[ 0. ],
[-1.2],
[-1.2],
[-3.4],
[-3.4],
[-4.5],
[-4.5]])
>>>
Upvotes: 7