1

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) or the first values at the bottom. (if they are down justified)

    [[False  True  True  True  True   True]
     [False  False True  True  False  True]
     [False  True  False True  False  False
     [True   True  True  True  False  True]]

So If I down justify the True values of the bool array shown above, it would look like:

[[False  False False True  False False]
 [False  True  True  True  False True]
 [False  True  True  True  False True]
 [True   True  True  True  True  True]]
PyManiac
  • 474
  • 4
  • 12
bnicholl
  • 306
  • 2
  • 13

2 Answers2

2

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)
Divakar
  • 218,885
  • 19
  • 262
  • 358
0

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 back
    return 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)
KAL
  • 50
  • 2