Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to move identical elements in numpy array into subarrays

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)
like image 429
themachinist Avatar asked Oct 23 '15 18:10

themachinist


1 Answers

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])]
like image 97
Divakar Avatar answered Sep 29 '22 13:09

Divakar