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

Jon Saenz jsaenz at wm.lc.ehu.es
Mon Mar 19 15:25:42 CST 2001


Probably this can help you.

Look in the manual about the ... operator, too.


bash-2.02$ python
Python 1.6b1 (#3, Aug 30 2000, 08:32:49)  [GCC 2.7.2.1] on freebsd3
Copyright (c) Corporation for National Research Initiatives.
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
>>> from Numeric import *
>>> a=array([[2,3],[4,5],[6,7]])
>>> b=array([9,10,11])
>>> a.shape
(3, 2)
>>> b.shape
(3,)
>>> print a+b[:,NewAxis]
[[11 12]
 [14 15]
 [17 18]]
>>>


Jon Saenz.				| Tfno: +34 946012470
Depto. Fisica Aplicada II               | Fax:  +34 944648500
Facultad de Ciencias.   \\ Universidad del Pais Vasco \\
Apdo. 644   \\ 48080 - Bilbao  \\ SPAIN

On Mon, 19 Mar 2001, Aureli Soria Frisch wrote:

> Hello!
> 
> 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.
> 
> So after testing a lot I found following solution:
> 
> A=Numeric.array(a)
> 
> A.shape=(a1,a2,...,ak,...,aN)	#where N is any int value
> 
> B=Numeric.array(b)
> B.shape=(ak,)
> 
> 
> A_modified=Numeric.reshape(A, (a1*a2*...*aN,ak)) #ak is not included in the
> product
> 
> result=[]
> for i in A_modified:
> 	result.append(i - B)
> 
> 
> and finally reshaping the result appropriately. But it does not seem
> neither elegant nor simple.
> 
> Is there any more elegant solution? The key point is: how to operate a N-D
> array with a 1D in one determined axis?
> 
> Thanks in advance.
> Regards,
> Aureli
> 
> 
> 
> 
> #################################
> Aureli Soria Frisch
> Fraunhofer IPK
> Dept. Pattern Recognition
> 
> post: Pascalstr. 8-9, 10587 Berlin, Germany
> e-mail:aureli at ipk.fhg.de
> fon: +49 30 39 00 61 50
> fax: +49 30 39 17 517
> #################################
> 
> 
> 
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at lists.sourceforge.net
> http://lists.sourceforge.net/lists/listinfo/numpy-discussion
> 





More information about the Numpy-discussion mailing list