How do I efficiently move identical elements from a sorted numpy array into subarrays?
from here:
import numpy as np
a=np.array([0,0,1,1,1,3,5,5,5])
to here:
a2=array([[0, 0], [1, 1, 1], [3], [5, 5, 5]], dtype=object)
One approach would be to get the places of shifts, where the numbers change and use those indices to split the input array into subarrays. For finding those indices, you can use np.nonzero on a differentiated array and then use np.split for splitting, like so -
np.split(a,np.nonzero(np.diff(a))[0]+1)
Sample run -
In [42]: a
Out[42]: array([2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6])
In [43]: np.split(a,np.nonzero(np.diff(a))[0]+1)
Out[43]:
[array([2, 2, 2, 2]),
array([3, 3, 3, 3]),
array([4, 4, 4, 4, 4, 4, 4]),
array([5, 5]),
array([6, 6, 6])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With