简体   繁体   中英

how to convert items of array into array themselves Python

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?

Or simply:

arr[:,None]

# array([[ 0. ],
#        [ 0. ],
#        [-1.2],
#        [-1.2],
#        [-3.4],
#        [-3.4],
#        [-4.5],
#        [-4.5]])

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM