# [SciPy-user] RE: [Numpy-discussion] Removing rows and columns of a matrix

Nils Wagner wagner.nils at vdi.de
Tue Jul 29 12:07: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.
>
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
view)

Perry

Perry,

familiar with numarray.

This is the output of my test program.

from scipy import *
from RandomArray import *
from numarray import *

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

a = rand(5,5)
print a
a = remove(a, 2)
print a

#to remove the 3th row or
#to remove the 3th column

a = remove(a, 2, dim=1)
print a

[[ 0.87329948  0.81829292  0.72929943  0.13012239  0.49291104]
[ 0.58665377  0.78030288  0.85906255  0.11409029  0.77719343]
[ 0.01325159  0.03389675  0.25417367  0.51117259  0.61979091]
[ 0.32406124  0.24500449  0.06147733  0.04323368  0.64497042]
[ 0.10133368  0.25028452  0.33645368  0.34395722  0.34052679]]
Traceback (most recent call last):
File "nils.py", line 19, in ?
a = remove(a, 2)
File "nils.py", line 8, in remove
swparr = swapaxes(arr, 0, dim)
File "/usr/lib/python2.2/site-packages/numarray/generic.py", line
855, in swapaxes
v = _nc.inputarray(array).view()
File "/usr/lib/python2.2/site-packages/numarray/numarraycore.py",
line 310, in inputarray
return array(seq, type=type, typecode=typecode, copy=0)
File "/usr/lib/python2.2/site-packages/numarray/numarraycore.py",
line 303, in array
raise ValueError("Unknown input type")
ValueError: Unknown input type

Any idea ?

Nils

_______________________________________________
SciPy-user mailing list
SciPy-user at scipy.net
http://www.scipy.net/mailman/listinfo/scipy-user

```