I have a numpy matrix like so:
array([[2, 1, 23, 32],
[34, 3, 3, 0],
[3, 33, 0, 0],
[32, 0, 0, 0]], dtype=int32)
Now
pandas method:
In [181]:
# construct df from array
df = pd.DataFrame(a)
# call apply and call np.roll rowise and roll by the number of zeroes
df.apply(lambda x: np.roll(x, (x == 0).sum()), axis=1).values
Out[181]:
array([[ 2, 1, 23, 32],
[ 0, 34, 3, 3],
[ 0, 0, 3, 33],
[ 0, 0, 0, 32]])
This uses apply
so we can call np.roll
on each row by the number of zeroes in each row