-1

I have the following NumPy array

[[  0 935]
 [  0 331]
 [  0 322]
 [  1 339]
 [  1 773]
 [  2 124]
 [  2 340]
 [  3 810]
 [  5 936]
 [  5 252]]

and would like to separate it into

[[  0 935]
 [  0 331]
 [  0 322]]

[[  1 339]
 [  1 773]]

[[  2 124]
 [  2 340]]

[[  3 810]]

[[  5 936]
 [  5 252]]

Are there any fast solutions to accomplish this?

2
  • Is there supposed to be a space between 0 935 or are they a list of length 2 Commented Jul 20, 2020 at 18:50
  • @AdityaMishra that is how numpy arrays print out Commented Jul 20, 2020 at 18:51

2 Answers 2

1

If all equal numbers located in one place you can do:

import numpy as np

a = np.array([[  0, 935],
 [  0, 331],
 [  0, 322],
 [  1, 339],
 [  1, 773],
 [  2, 124],
 [  2, 340],
 [  3, 810],
 [  5, 936],
 [  5, 252],])
print(np.array_split(a, np.flatnonzero(np.diff(a[:, 0])) + 1))
# [array([[  0, 935],
#        [  0, 331],
#        [  0, 322]]), array([[  1, 339],
#        [  1, 773]]), array([[  2, 124],
#        [  2, 340]]), array([[  3, 810]]), array([[  5, 936],
#        [  5, 252]])]

otherwise you can first sort array:

import numpy as np

a = np.array([[  0, 935],
 [  5, 936],
 [  2, 124],
 [  2, 340],
 [  5, 252],])
a.sort(axis=0)
print(*np.array_split(a, np.flatnonzero(np.diff(a[:, 0])) + 1), sep="\n")
# [[  0 124]]
# [[  2 252]
#  [  2 340]]
# [[  5 935]
#  [  5 936]]
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this :

# Note: k is your array
import numpy as np
k = np.array([[  0, 935],[  0, 331],[  0, 322],
             [ 1, 339],[  1, 773],[  2, 124],
             [  2, 340],[  3, 810],[  5, 936],
             [  5, 252]])

# sort  indices
indices = np.argsort(k[:, 0])

# use indices to get sorted array
arr_temp = k[indices]

# retrieve your answer
net = np.array_split(arr_temp, 
      np.where(np.diff(arr_temp[:,0])!=0)[0]+1)
net[0]

This solution was inspired from How to split a numpy array based on a column?

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.