Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove zero lines 2-D numpy array

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

>>> [q,r] = np.linalg.qr(np.array([1,0,0,0,1,1,1,1,1]).reshape(3,3)) 

R is a two-dimensional array, having pivoted zero-lines at the bottom (even proved for all examples in my test set):

>>> print r [[ 1.41421356  0.70710678  0.70710678]  [ 0.          1.22474487  1.22474487]  [ 0.          0.          0.        ]] 

. Now, I want to divide R in two matrices R_~:

[[ 1.41421356  0.70710678  0.70710678]  [ 0.          1.22474487  1.22474487]] 

and R_0:

[[ 0.          0.          0.        ]] 

(extracting all zero-lines). It seems to be close to this solution: deleting rows in numpy array.

EDIT:
Even more interesting: np.linalg.qr() returns a n x n-matrix. Not, what I would have expected:

A := n x m Q := n x m R := n x m 
like image 446
Milla Well Avatar asked Jun 25 '12 11:06

Milla Well


People also ask

How do I delete multiple rows in NumPy?

delete() – The numpy. delete() is a function in Python which returns a new array with the deletion of sub-arrays along with the mentioned axis. By keeping the value of the axis as zero, there are two possible ways to delete multiple rows using numphy. delete().

How do I remove part of a NumPy array?

To remove an element from a NumPy array: Specify the index of the element to remove. Call the numpy. delete() function on the array for the given index.

What is the use of zeros () function in NumPy?

The zeros() function is used to get a new array of given shape and type, filled with zeros. Shape of the new array, e.g., (2, 3) or 2. The desired data-type for the array, e.g., numpy. int8.


2 Answers

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]]) 
like image 169
ecatmur Avatar answered Oct 05 '22 18:10

ecatmur


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) 
like image 31
HYRY Avatar answered Oct 05 '22 17:10

HYRY