在python和matlab中切割矩阵

在成为MATLAB用户多年后,我现在正在迁移到
python.

我试着找到一种简洁的方式来简单地在python中重写以下MATLAB代码:

s = sum(Mtx);
newMtx = Mtx(:, s>0);

其中Mtx是2D稀疏矩阵

我的python解决方案是:

s = Mtx.sum(0)
newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices

其中Mtx是2D CSC稀疏矩阵

python代码不像matlab那样可读/优雅..任何想法如何更优雅地编写它?

谢谢!

最佳答案 尝试这样做:

s = Mtx.sum(0);
newMtx = Mtx[:,nonzero(s.T > 0)[0]] 

资料来源:http://wiki.scipy.org/NumPy_for_Matlab_Users#head-13d7391dd7e2c57d293809cff080260b46d8e664

与您的版本相比,它不那么模糊,但根据指南,这是您将获得的最好的!

点赞