[SciPy-User] delete rows and columns

Chris Weisiger cweisiger@msg.ucsf....
Wed Mar 14 10:23:39 CDT 2012

On Wed, Mar 14, 2012 at 3:16 AM, Lee <lchaplin13@gmail.com> wrote:
> Hi all,
> first time here, sorry if I am not posting in the right group.
> I am trying to run the below example from numpy docs:
> import numpy as np
> print np.version.version #1.6.1 (win7-64, py2.6)
> a = np.array([0, 10, 20, 30, 40])
> np.delete(a, [2,4]) # remove a[2] and a[4]
> print a
> a = np.arange(16).reshape(4,4)
> print a
> np.delete(a, np.s_[1:3], axis=0) # remove rows 1 and 2
> print a
> np.delete(a, np.s_[1:3], axis=1) # remove columns 1 and 2
> print a
> Basically I am trying to delete some column/rows from an array or a
> matrix.
> It seems that delete doesn't work I expect (and advertised). Am I
> missing something?

Numpy arrays are continuous blocks of memory, so doing an in-place
deletion would require allocating a new block and copying everything
that isn't deleted over. numpy.delete does exactly that. It doesn't
modify the original array; it creates a copy of the non-deleted
portions and returns that.

If you run the above program in Python's REPL, then you'd see this:

>>> a = np.array([0, 10, 20, 30, 40])
>>> np.delete(a, [2, 4])
array([ 0, 10, 30])
>>> print a
[ 0 10 20 30 40]

Note how there's a result from running np.delete(), which gets printed
by default in the REPL.

Instead of allocating a new chunk of memory that's just a copy of most
of the old chunk, you can accomplish a similar feat using array

>>> a[[0,1,3]] # Everything in a except columns 2 and 4
array([ 0, 10, 30])

You could assign that back to a, and then be able to treat a as if
those two columns had been erased (since they'd be functionally
inaccessible). I assume this would make lookups into the array a bit
slower though, because now behind the scenes Numpy has to know to skip
over those blocks of memory that you've elided. It's all a question of
if CPU or RAM is more precious.


> Thanks,
> Lee
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user

More information about the SciPy-User mailing list