splitting an array where it meets the peak values

Viewed 160

hope doing well. I have an extremely big numpy array and want to split it into several ones. My array has three columns and I want to split it where the all the columns are reaching their maximum values:

array = [[0, 0, 0],
         [0, 0, 5],
         [10, 5, 10],
         [1, 1, 1],
         [5, 5, 15],
         [10, 8, 20],
         [2, 0, 0],
         [10, 10, 12],
         [1, 2, 0],
         [2, 5, 9]]

Now, I want to split it into four array:

sub_array_1=[[0, 0, 0],
         [0, 0, 5],
         [10, 5, 10]]
sub_array_2=[[1, 1, 1],
         [5, 5, 15],
         [10, 8, 20]]
sub_array_3=[[2, 0, 0],
         [10, 10, 12]]
sub_array_4=[[1, 2, 0],
         [2, 5, 9]]

I tried to it in a for loop having if statements saying that give me an array when each element of my input is bigger than the element stored in the both upper and lower rows. And I also should figure out the last row:

import numpy as np    
sub_array_1=np.array([])
    for i in array:
        if array[i,:]>array[i+1,:] and array[i,:]>array[i+1,:]:
            vert_1=np.append(sub_array_1,array[0:i,:])

My code doesn't work, but it simply shows my idea. I am quite new in Python and I could not find the way to write my idea as a code. So, I appreciate any help and contribution. Cheers, Ali

1 Answers

IIUC, one way using numpy.diff with numpy.array_split:

indices = np.argwhere(np.all(np.diff(array, axis=0) < 0, axis=1))
np.array_split(array, indices.ravel()+1, axis=0)

Output:

[array([[ 0,  0,  0],
        [ 0,  0,  5],
        [10,  5, 10]]),
 array([[ 1,  1,  1],
        [ 5,  5, 15],
        [10,  8, 20]]),
 array([[ 2,  0,  0],
        [10, 10, 12]]),
 array([[1, 2, 0],
        [2, 5, 9]])]
  • np.all and np.diff find a row where all elements of the row as a negative difference with a next row (i.e. where the peak ends)
  • np.array_split will then split the given array based on the locations of the peak found.
Related