4

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?

4 Answers 4

13

Or simply:

arr[:,None]

# array([[ 0. ],
#        [ 0. ],
#        [-1.2],
#        [-1.2],
#        [-3.4],
#        [-3.4],
#        [-4.5],
#        [-4.5]])
Sign up to request clarification or add additional context in comments.

4 Comments

Same as a1[:,np.newaxis]. None in a np slice is synonymous to np.newaxis
@utkarsh13 Honestly, I can't explain this better than the doc docs.scipy.org/doc/numpy/reference/…. Basically, None means creating a newaxis here.
@OrB Works on Python 2 as well.
@Psidom OK, I thought it should work for any list. Turns out it works for numpy arrays only.
7

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

Comments

6

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

Comments

1

There are several ways to achieve this with 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]])
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.