[Numpy-discussion] Suggestion: Add the unsqueeze function to numpy

josef.pktd at gmail.com josef.pktd at gmail.com
Wed Apr 20 14:27:10 EDT 2011


On Wed, Apr 20, 2011 at 2:19 PM, Daniel Lepage <dplepage at gmail.com> wrote:
> You can also insert new axes when you slice an array via np.newaxis, fwiw:
>
>>>> import numpy as np
>>>> x = np.random.random((3,4,5))
>>>> y = x.mean(axis=1)
>>>> y.shape
> (3, 5)
>>>> y[:,np.newaxis,:].shape
> (3, 1, 5)

That's convenient if you only have a specific axis to take care of,
but I like expand_dims when I write functions that are supposed to
work with any axis.

def demean(x, axis=0):
    return x - np.expand_dims(x.mean(axis), axis)

or something like this

Josef

> --
> Dan Lepage
>
> On Wed, Apr 20, 2011 at 1:24 PM, Yannick Copin
> <yannick.copin at laposte.net> wrote:
>>  <josef.pktd <at> gmail.com> writes:
>>> I also proposed this already once.
>>>
>>> However there is already function in numpy  (where I have often
>>> problems remembering the name):
>>>
>>> numpy.expand_dims(a, axis)
>>
>> Ah, thanks for the tip, I didn't know this one. The name is unfortunate indeed...
>>
>> Cheers,
>>
>> Yannick
>>
>>
>>
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion at scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>



More information about the NumPy-Discussion mailing list