If I have an numpy array like the one below, how can I right justify or left justify the elements tat are greater than zero
[[ 0. 5. 0. 2.]
[ 0. 0. 3.
import numpy as np
array = [
[ 0., 5., 0., 2.],
[ 0., 0., 3., 2.],
[ 0., 0., 0., 0.],
[ 2., 0., 0., 1.]
]
def move(array, right = True):
temp = []
for x in array:
x = np.array(x)
#check positive arrays
if len(np.where(x == 0)[0]) != len(x):
if right:
# little faster, compare to [::-1]
# nonzero on right
temp.append(x[np.argsort(-x)])
else:
# nonzero on left
temp.append(np.sort(x))
else:
# no interchange needed
temp.append(x)
return temp
print (move(array, 1))
[array([ 5., 2., 0., 0.]), array([ 3., 2., 0., 0.]), array([ 0., 0., 0., 0.]), array([ 2., 1., 0., 0.])]
print (move(array, 0))
[array([ 0., 0., 2., 5.]), array([ 0., 0., 2., 3.]), array([ 0., 0., 0., 0.]), array([ 0., 0., 1., 2.])]
print (np.concatenate(list(zip(move(array, 1))), axis=0))
[[ 5. 2. 0. 0.]
[ 3. 2. 0. 0.]
[ 0. 0. 0. 0.]
[ 2. 1. 0. 0.]]