我有一个像这样的矩阵M:
>>> M
array([[1, 0, 3, 4],
[0, 3, 4, 5],
[5, 4, 0, 7]])
我想要做的是提取M中每行的第一个N(比如说N = 2)非零元素,并将它们放入相同形状的新矩阵M2中,同时设置匹配值M为零。所以输出应该是:
>>> M
array([[0, 0, 0, 4],
[0, 0, 0, 5],
[0, 0, 0, 7]])
>>> M2
array([[1, 0, 3, 0],
[0, 3, 4, 0],
[5, 4, 0, 0]])
答案 0 :(得分:3)
使用cumsum
-
M2 = M*((M!=0).cumsum(1)<=2)
M_new = M - M2
示例运行 -
In [42]: M
Out[42]:
array([[1, 0, 3, 4],
[0, 3, 4, 5],
[5, 4, 0, 7]])
In [43]: M2 = M*((M!=0).cumsum(1)<=2)
...: M_new = M - M2
...:
In [44]: M_new
Out[44]:
array([[0, 0, 0, 4],
[0, 0, 0, 5],
[0, 0, 0, 7]])
In [45]: M2
Out[45]:
array([[1, 0, 3, 0],
[0, 3, 4, 0],
[5, 4, 0, 0]])