[Numpy-discussion] Removing rows and columns of a matrix

Perry Greenfield perry at stsci.edu
Tue Jul 29 11:25:03 CDT 2003

Nils Wagner writes:
> In any case I am interested in a reliable workaround for this feature.
> A small example would be appreciated.
> Thanks in advance.
Numarray (and Numeric to a certain extent) currently is
centered around what rows or columns you want rather than
those you don't. Writing a reasonably efficient function
to do this in a more convenient way is not hard. Here is
an example for numarray (not tested, nor does it have
any error checking to ensure the input array has sufficient
dimensions or that the index is within the array bounds):

def remove(arr, index, dim=0):
    """Remove subarray at index and dimension specified"""
    # make selected dimension the first one
    swparr = swapaxes(arr, 0, dim)
    indices = range(swparr.shape[0])
    del indices[index]
    newarray = swparr[indices]
    # reorder axes as they originally appeared.
    return swapaxes(newarray, 0, dim)	

Then you can say

x = remove(x, 5)

to remove the 6th row or

x = remove(x, 4, dim=1)

to remove the 5th column.
(depending on what you call rows or columns; in the examples
I'm taking an image-oriented view rather than a matrix-oriented


More information about the Numpy-discussion mailing list