remove zero lines 2-D numpy array

前端 未结 3 1966
旧时难觅i
旧时难觅i 2020-12-01 04:07

I run a qr factorization in numpy which returns a list of ndarrays, namely Qand R:

>>&         


        
相关标签:
3条回答
  • 2020-12-01 04:47

    Use np.all with an axis argument:

    >>> r[np.all(r == 0, axis=1)]
    array([[ 0.,  0.,  0.]])
    >>> r[~np.all(r == 0, axis=1)]
    array([[-1.41421356, -0.70710678, -0.70710678],
           [ 0.        , -1.22474487, -1.22474487]])
    
    0 讨论(0)
  • 2020-12-01 04:59

    Because the data are not equal zero exactly, we need set a threshold value for zero such as 1e-6, use numpy.all with axis=1 to check the rows are zeros or not. Use numpy.where and numpy.diff to get the split positions, and call numpy.split to split the array into a list of arrays.

    import numpy as np
    [q,r] = np.linalg.qr(np.array([1,0,0,0,1,1,1,1,1]).reshape(3,3))
    mask = np.all(np.abs(r) < 1e-6, axis=1)
    pos = np.where(np.diff(mask))[0] + 1
    result = np.split(r, pos)
    
    0 讨论(0)
  • 2020-12-01 05:11

    If you want to eliminate rows that have negligible entries, i'd use np.allclose.

    zero_row_indices = [i for i in r.shape[0] if np.allclose(r[i,:],0)]
    nonzero_row_indices =[i for i in r.shape[0] if not np.allclose(r[i,:],0)]
    r_new = r[nonzero_row_indices,:]
    
    0 讨论(0)
提交回复
热议问题