麻木矩阵.将所有 0 移动到每一行的末尾 [英] numpy matrix. move all 0's to the end of each row

查看:56
本文介绍了麻木矩阵.将所有 0 移动到每一行的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个在 python numpy 中的矩阵,它的某些行有前导零.我需要将所有零移到行尾.例如

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

应该转化为

2 3 4 0
1 5 0 0
2 3 1 1

在 python numpy 中有什么好的方法可以做到这一点吗?

Is there any nice way to do this in python numpy?

推荐答案

修复前导零行 -

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://stackoverflow.com/a/42859463/3293881
    valid_mask = a!=0
    flipped_mask = valid_mask.sum(1,keepdims=1) > np.arange(a.shape[1]-1,-1,-1)
    flipped_mask = flipped_mask[:,::-1]
    a[flipped_mask] = a[valid_mask]
    a[~flipped_mask] = 0
    return a

样品运行 -

In [220]: a
Out[220]: 
array([[0, 2, 3, 4],
       [0, 0, 1, 5],
       [2, 3, 1, 1]])

In [221]: fix_leading_zero_rows(a)
Out[221]: 
array([[2, 3, 4, 0],
       [1, 5, 0, 0],
       [2, 3, 1, 1]])

In [266]: a
Out[266]: 
array([[0, 2, 3, 4, 0],
       [0, 0, 1, 5, 6],
       [2, 3, 0, 1, 0]])

In [267]: push_all_zeros_back(a)
Out[267]: 
array([[2, 3, 4, 0, 0],
       [1, 5, 6, 0, 0],
       [2, 3, 1, 0, 0]])

这篇关于麻木矩阵.将所有 0 移动到每一行的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆