Home > Enterprise >  Is there an efficient way of splitting a 2-D numpy array(an array of coordinates) to two 1-D numpy a
Is there an efficient way of splitting a 2-D numpy array(an array of coordinates) to two 1-D numpy a

Time:03-16

Here is my array and I would like to separate it to two arrays, one contains all first values of pairs and one with all second values of pairs. Is there an efficient way to do that?

array([[-0.43042553, -0.1224234 ],
       [-2.03524537,  0.56015045],
       [ 1.40186973, -0.74534088],
       [-0.04612834, -0.43374017],
       [-0.71154051, -0.54219998],
       [-0.10434967, -0.80116922],
       [-0.28625899, -1.15067218],
       [ 2.18190517,  0.52953827]])

CodePudding user response:

Similar to other answers but more concise:

a1, a2 = arr.T

CodePudding user response:

here is how you do it.

>>> arr = np.array([[-0.43042553, -0.1224234 ],
...        [-2.03524537,  0.56015045],
...        [ 1.40186973, -0.74534088],
...        [-0.04612834, -0.43374017],
...        [-0.71154051, -0.54219998],
...        [-0.10434967, -0.80116922],
...        [-0.28625899, -1.15067218],
...        [ 2.18190517,  0.52953827]])
>>>
>>> arr
array([[-0.43042553, -0.1224234 ],
       [-2.03524537,  0.56015045],
       [ 1.40186973, -0.74534088],
       [-0.04612834, -0.43374017],
       [-0.71154051, -0.54219998],
       [-0.10434967, -0.80116922],
       [-0.28625899, -1.15067218],
       [ 2.18190517,  0.52953827]])
>>> a1, a2 = arr[:,0], arr[:,1]
>>> a1
array([-0.43042553, -2.03524537,  1.40186973, -0.04612834, -0.71154051,
       -0.10434967, -0.28625899,  2.18190517])
>>> a2
array([-0.1224234 ,  0.56015045, -0.74534088, -0.43374017, -0.54219998,
       -0.80116922, -1.15067218,  0.52953827])

CodePudding user response:

You can just slice

arr = np.array([[-0.43042553, -0.1224234 ],
                [-2.03524537,  0.56015045],
                [ 1.40186973, -0.74534088],
                [-0.04612834, -0.43374017],
                [-0.71154051, -0.54219998],
                [-0.10434967, -0.80116922],
                [-0.28625899, -1.15067218],
                [ 2.18190517,  0.52953827]])
arr1, arr2 = arr[:, 0], arr[:, 1]
  • Related