'Is there an efficient way of splitting a 2-D numpy array(an array of coordinates) to two 1-D numpy arrays?
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]])
Solution 1:[1]
Similar to other answers but more concise:
a1, a2 = arr.T
Solution 2:[2]
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])
Solution 3:[3]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Julien |
| Solution 2 | balu |
| Solution 3 | bokgae |
