Skip to content Skip to sidebar Skip to footer

Python: Up And Down Justify The Index Of A Bool Numpy Array

How can I up and down justify a numpy bool array. By Justify, I mean take the True values, and move them so they are either the first values at the top (if they are up justified) o

Solution 1:

Simply sort it along each column, which pushes down the True values, while brings up the False ones for down-justified version. For up-justified one, do a flipping on the sorted version.

Sample run to showcase the implementation -

In [216]: mask
Out[216]: 
array([[False,  True,  True,  True,  True,  True],
       [False, False,  True,  True, False,  True],
       [False,  True, False,  True, False, False],
       [ True,  True,  True,  True, False,  True]], dtype=bool)

In [217]: np.sort(mask,0)  # Down justified
Out[217]: 
array([[False, False, False,  True, False, False],
       [False,  True,  True,  True, False,  True],
       [False,  True,  True,  True, False,  True],
       [ True,  True,  True,  True,  True,  True]], dtype=bool)

In [218]: np.sort(mask,0)[::-1]   # Up justified
Out[218]: 
array([[ True,  True,  True,  True,  True,  True],
       [False,  True,  True,  True, False,  True],
       [False,  True,  True,  True, False,  True],
       [False, False, False,  True, False, False]], dtype=bool)

Solution 2:

It looks like you want to move the first array to the back to do what you're calling "up justifying". I think it's a little difficult to rearrange the elements in a numpy array, so I usually convert to a standard python list, rearrange the elements, and convert back to a numpy array.

def up_justify(np_array):
    list_array =list(np_array)
    first_list = list_array.pop(0) #removes first list
    list_array.append(first_list) #adds list to backreturn np.array(list_array)

Similarly, you can down justify by removing the last list and placing it at the front, like so

def down_justify(np_array):
    list_array =list(np_array)
    last_element = list_array.pop()
    return np.array([last_element] + list_array)

Post a Comment for "Python: Up And Down Justify The Index Of A Bool Numpy Array"