Swap zeros in numpy matrix

后端 未结 6 1182
眼角桃花
眼角桃花 2021-01-20 13:08

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

6条回答
  •  盖世英雄少女心
    2021-01-20 13:58

    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

提交回复
热议问题