numpy matrix. move all 0's to the end of each row
问题 Given a matrix in python numpy which has for some of its rows, leading zeros. I need to shift all zeros to the end of the line. E.g. 0 2 3 4 0 0 1 5 2 3 1 1 should be transformed to 2 3 4 0 1 5 0 0 2 3 1 1 Is there any nice way to do this in python numpy? 回答1: To fix for leading zeros rows - def fix_leading_zeros(a): mask = a!=0 flipped_mask = mask[:,::-1] a[flipped_mask] = a[mask] a[~flipped_mask] = 0 return a To push all zeros rows to the back - def push_all_zeros_back(a): # Based on http:/