[Numpy-discussion] How operating arrays in a determined axis?

Konrad Hinsen hinsen at cnrs-orleans.fr
Tue Mar 20 09:17:08 EST 2001


> I have a N-dimensional array A and I want to operate in one of the axis (k)
> with a 1 dimensional array (for instance,  subtracting an array B of length
> k). I have looked for some solutions in the manual and did not found any.

I am not sure that I understand your problem exactly, but here's the solution
to what I think your problem is ;-)

  from Scientific.indexing import index_expression
  import Numeric

  indices = index_expression[::] + \
	    (len(A.shape)-k-1)*index_expression[Numeric.NewAxis]
  result = A-B[indices]

This uses a module from ScientificPython which provides syntactic sugar
for indexing. In fact, the module is so simple that I include it here:

---------------------------------------------------------------------------
# A nicer way to build up index tuples for arrays.
#
# You can do all this with slice() plus a few special objects,
# but there's a lot to remember. This version is simpler because
# it uses the standard array indexing syntax.
#
# Written by Konrad Hinsen <hinsen at cnrs-orleans.fr>
# last revision: 1999-7-23
#

"""This module provides a convenient method for constructing
array indices algorithmically. It provides one importable object,
'index_expression'.

For any index combination, including slicing and axis insertion,
'a[indices]' is the same as 'a[index_expression[indices]]' for any
array 'a'. However, 'index_expression[indices]' can be used anywhere
in Python code and returns a tuple of indexing objects that can be
used in the construction of complex index expressions.

Sole restriction: Slices must be specified in the double-colon
form, i.e. a[::] is allowed, whereas a[:] is not.
"""

class _index_expression_class:

    import sys
    maxint = sys.maxint

    def __getitem__(self, item):
        if type(item) != type(()):
            return (item,)
        else:
            return item

    def __len__(self):
	return self.maxint

    def __getslice__(self, start, stop):
	if stop == self.maxint:
	    stop = None
	return self[start:stop:None]

index_expression = _index_expression_class()
---------------------------------------------------------------------------

Konrad.
-- 
-------------------------------------------------------------------------------
Konrad Hinsen                            | E-Mail: hinsen at cnrs-orleans.fr
Centre de Biophysique Moleculaire (CNRS) | Tel.: +33-2.38.25.56.24
Rue Charles Sadron                       | Fax:  +33-2.38.63.15.17
45071 Orleans Cedex 2                    | Deutsch/Esperanto/English/
France                                   | Nederlands/Francais
-------------------------------------------------------------------------------




More information about the NumPy-Discussion mailing list