1

I have a Numpy 1D vector, for example x = [1, 1, 1, 2, 2, 1, 3, 3, 1]

I have to perform a splitting of it into n subarrays, where each vector must start with a new value and continue for as long as the value is the same, such that the final answer is [[1, 1, 1], [2, 2], [1], [3, 3], [1]].

I do understand that I have to use numpy.split() function, but I have problems with finding the places at which the splitting must be done.

I humbly ask of your help, thanks for your time!

1 Answer 1

1

You just need to give numpy.split the indexes you need it to split the array

a = np.array([1,1,1,2,2,1,3,3,1])
np.split(a, np.argwhere(np.diff(a) != 0)[:,0] + 1)
# [array([1, 1, 1]), array([2, 2]), array([1]), array([3, 3]), array([1])]

Details

Using np.diff(a) you get the differences between each consecutive element

np.diff(a)
# array([ 0,  0,  1,  0, -1,  2,  0, -2])

The points where the differences are not equal to 0 is the points where the elements are not consecutively the same. Since you are looking for the indexes where the changes you need to do np.diff(a) != 0 which returns:

np.diff(a) != 0
# array([False, False,  True, False,  True,  True, False,  True])

To convert the booleans into the indexes you can use np.argwhere

np.argwhere(np.diff(a) != 0)
# array([[2],[4],[5],[7]])
# since we only need this for 1d arrays
np.argwhere(np.diff(a) != 0)[:,0]
# array([2, 4, 5, 7])

The you just use the aforementioned procedure to provide the correct indexes to np.split

np.split(a, np.argwhere(np.diff(a) != 0)[:,0])
# [array([1, 1]), array([1, 2]), array([2]), array([1, 3]), array([3, 1])]

Woops... wrong indexes... Seems we are off by 1 index. No problem, just add +1 to the results of np.argwhere

np.split(a, np.argwhere(np.diff(a) != 0)[:,0] + 1)
# [array([1, 1, 1]), array([2, 2]), array([1]), array([3, 3]), array([1])]
Sign up to request clarification or add additional context in comments.

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.