NumPy arrays: how to remove extra axes

Janko Hauser jhauser at ifm.uni-kiel.de
Tue Jun 13 03:33:02 EDT 2000


Tim Hochberg <tim.hochberg at ieee.org> writes:

> hzhu at rocket.knowledgetrack.com (Huaiyu Zhu) writes:
> 
> > For arrays in Numeric, is there a general way to remove axes of length 1?
> > For example I have an array of shape (1,3,1,4) I want to change it to (3,4).
> > Thanks
> > 
> > 
> > Huaiyu Zhu                               hzhu at knowledgetrack.com
> 
> Here's a function I just tossed together that should do what you
> want. It's only barely tested, so I'd beat on it a bit before trusting
> it.
> 
> -tim
> 
> --------------------------------------
> 
> from Numeric import *
> 
> def compactAxes(A):
>     """Return an array with axes of length 1 removed"""
>     index = []
>     for length in shape(A):
>         if length == 1:
>             index.append(0)
>         else:
>             index.append(slice(None))
>     return A[tuple(index)]
> 
> --------------------------------------
> 
The above function always makes a copy of the data. The next one only
changes the shape.

def DelAxis(m):
    """
    Removes all axis with length one
    """
    sh = m.shape
    new_shape=[]
    for axis_length in sh:
	if axis_length > 1:
	    new_shape.append(axis_length)
    return Numeric.reshape(m,new_shape)

HTH,
__Janko


-- 
  Institut fuer Meereskunde             phone: 49-431-597 3989
  Dept. Theoretical Oceanography        fax  : 49-431-565876
  Duesternbrooker Weg 20                email: jhauser at ifm.uni-kiel.de
  24105 Kiel, Germany



More information about the Python-list mailing list