Questions on migrating from Numeric/Scipy to Numpy

Robert Kern robert.kern at gmail.com
Tue Mar 13 22:06:59 EDT 2007


vj wrote:
> I've tried to post this to the numpy google group but it seems to be
> down.

It is just a redirection to the numpy-discussion at scipy.org list. If you just
tried in the past hour or so, I've discovered that our DNS appears to be down
right now.

> My migration seems to be going well. I currently have one issue
> with using scipy_base.insert.
> 
>>>> a = zeros(5)
>>>> mask = zeros(5)
>>>> mask[1] = 1
>>>> c = zeros(1)
>>>> c[0] = 100
>>>> numpy.insert(a, mask, c)
> array([ 100.,    0.,  100.,  100.,  100.,    0.,    0.,    0.,
> 0.,    0.])
>>>> a
> array([ 0.,  0.,  0.,  0.,  0.])
>>>> b
> array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1], dtype=int8)
>>>> mask
> array([ 0.,  1.,  0.,  0.,  0.])
>>>> c
> array([ 100.])
> 
> I would have expected numpy.insert to update a so that the second
> element in a would be 100.

No, that's not what insert() does. See the docstring:

In [1]: from numpy import *

In [2]: insert?
Type:             function
Base Class:       <type 'function'>
Namespace:        Interactive
File:
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/numpy-1.0.2.dev3569-py2.5-macosx-10.3-fat.egg/numpy/lib/function_base.py
Definition:       insert(arr, obj, values, axis=None)
Docstring:
    Return a new array with values inserted along the given axis
    before the given indices

    If axis is None, then ravel the array first.

    The obj argument can be an integer, a slice, or a sequence of
    integers.

    Example:
    >>> a = array([[1,2,3],
    ...            [4,5,6],
    ...            [7,8,9]])

    >>> insert(a, [1,2], [[4],[5]], axis=0)
    array([[1, 2, 3],
           [4, 4, 4],
           [4, 5, 6],
           [5, 5, 5],
           [7, 8, 9]])


The behaviour that you seem to want would be accomplished with the following:

In [3]: a = zeros(5)

In [4]: mask = zeros(5, dtype=bool)

In [5]: mask[1] = True

In [6]: mask
Out[6]: array([False,  True, False, False, False], dtype=bool)

In [7]: a[mask] = 100

In [8]: a
Out[8]: array([   0.,  100.,    0.,    0.,    0.])


Note that the mask needs to be a bool array.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list