Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify vectors with same value in one column with numpy in python

I have a large 2d array of vectors. I want to split this array into several arrays according to one of the vectors' elements or dimensions. I would like to receive one such small array if the values along this column are consecutively identical. For example considering the third dimension or column:

orig = np.array([[1, 2, 3], 
                 [3, 4, 3], 
                 [5, 6, 4], 
                 [7, 8, 4], 
                 [9, 0, 4], 
                 [8, 7, 3], 
                 [6, 5, 3]])

I want to turn into three arrays consisting of rows 1,2 and 3,4,5 and 6,7:

>>> a
array([[1, 2, 3],
       [3, 4, 3]])

>>> b
array([[5, 6, 4],
       [7, 8, 4],
       [9, 0, 4]])

>>> c
array([[8, 7, 3],
       [6, 5, 3]])

I'm new to python and numpy. Any help would be greatly appreciated.

Regards Mat

Edit: I reformatted the arrays to clarify the problem

like image 254
Mathew Avatar asked Feb 11 '23 04:02

Mathew


1 Answers

Using np.split:

>>> a, b, c = np.split(orig, np.where(orig[:-1, 2] != orig[1:, 2])[0]+1)

>>> a
array([[1, 2, 3],
       [1, 2, 3]])
>>> b
array([[1, 2, 4],
       [1, 2, 4],
       [1, 2, 4]])
>>> c
array([[1, 2, 3],
       [1, 2, 3]])
like image 81
Jaime Avatar answered Feb 12 '23 17:02

Jaime