[Numpy-discussion] add axis to results of reduction (mean, min, ...)

josef.pktd@gmai... josef.pktd@gmai...
Thu Aug 6 11:21:26 CDT 2009


On Thu, Aug 6, 2009 at 12:07 PM, Robert Kern<robert.kern@gmail.com> wrote:
> On Thu, Aug 6, 2009 at 11:03, Keith Goodman<kwgoodman@gmail.com> wrote:
>> On Thu, Aug 6, 2009 at 8:55 AM, <josef.pktd@gmail.com> wrote:
>>> What's the best way of getting back the correct shape to be able to
>>> broadcast, mean, min,.. to the original array, that works for
>>> arbitrary dimension and axis?
>>>
>>> I thought I have seen some helper functions, but I don't find them anymore?
>>>
>>> Josef
>>>
>>>>>> a
>>> array([[1, 2, 3, 3, 0],
>>>       [2, 2, 3, 2, 1]])
>>>>>> a-a.max(0)
>>> array([[-1,  0,  0,  0, -1],
>>>       [ 0,  0,  0, -1,  0]])
>>>>>> a-a.max(1)
>>> Traceback (most recent call last):
>>>  File "<pyshell#135>", line 1, in <module>
>>>    a-a.max(1)
>>> ValueError: shape mismatch: objects cannot be broadcast to a single shape
>>>>>> a-a.max(1)[:,None]
>>> array([[-2, -1,  0,  0, -3],
>>>       [-1, -1,  0, -1, -2]])
>>
>> Would this do it?
>>
>>>> pylab.demean??
>> Type:           function
>> Base Class:     <type 'function'>
>> String Form:    <function demean at 0x3c5c050>
>> Namespace:      Interactive
>> File:           /usr/lib/python2.6/dist-packages/matplotlib/mlab.py
>> Definition:     pylab.demean(x, axis=0)
>> Source:
>> def demean(x, axis=0):
>>    "Return x minus its mean along the specified axis"
>>    x = np.asarray(x)
>>    if axis:
>>        ind = [slice(None)] * axis
>>        ind.append(np.newaxis)
>>        return x - x.mean(axis)[ind]
>>    return x - x.mean(axis)
>
> Ouch! That doesn't handle axis=-1.
>
> if axis != 0:
>    ind = [slice(None)] * x.ndim
>    ind[axis] = np.newaxis
>

Thanks, that's it.

I have seen implementation of helper functions similar to this in
other packages, but I thought there is already something in numpy.  I
think this should be a simple helper function in numpy to avoid
mistakes and complicated implementation like the one in stats.nanstd
even if it's only a few lines.

Josef


> --
> 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
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>


More information about the NumPy-Discussion mailing list