[Numpy-discussion] How to remove any row or column of a numpy matrix whose sum is 3?

Robert Kern robert.kern at gmail.com
Mon Jun 4 12:38:05 EDT 2012

On Mon, Jun 4, 2012 at 5:21 PM, bob tnur <bobtnur78 at gmail.com> wrote:
> Hello every body. I am new to python.
> How to remove any row or column of a numpy matrix whose sum is 3.
> To obtain and save new matrix P with (sum(anyrow)!=3 and sum(anycolumn)!=3
> elements.
> I tried like this:
> P = M[np.logical_not( (M[n,:].sum()==3) & (M[:,n].sum()==3))]
> or
> P = M[np.logical_not( (np.sum(M[n,:])==3) & (np.sum(M[:,n])==3))]
> M is the nxn numpy matrix.
> But I got indexerror. So can anyone correct this or any other elegant way of
> doing this?

If M is 5x5 matrix, then M[5,:] and M[:,5] don't work. You can't index
past the last element. Python sequences in general and numpy arrays in
particular use 0-based indexing. I'm not entirely sure what you
intended with those expressions anyways.

Here is how I would do it.

  # Get the integer indices of the rows that sum up to 3
  # and the columns that sum up to 3.
  bad_rows = np.nonzero(M.sum(axis=1) == 3)
  bad_cols = np.nonzero(M.sum(axis=0) == 3)

  # Now use the numpy.delete() function to get the matrix
  # with those rows and columns removed from the original matrix.
  P = np.delete(M, bad_rows, axis=0)
  P = np.delete(P, bad_cols, axis=1)

Robert Kern

More information about the NumPy-Discussion mailing list