[Numpy-discussion] iterate over multiple arrays
Sturla Molden
sturla at molden.no
Tue Sep 13 17:28:39 EDT 2011
Den 12.09.2011 08:52, skrev David Froger:
> Hy everybody,
>
> I'm wondering what is the (best) way to apply the same function to multiple
> arrays.
>
I tried to experiment a bit with this. Here is from an ipython session:
Create some arrays:
In [1]: import numpy as np
In [2]: a = np.zeros(4)
In [3]: b = a+1
In [4]: c = a+2
In [5]: d = a+3
Create an array with dtype=object to store the four arrays a-d:
In [6]: e = np.zeros(4, dtype=object)
In [7]: e[:] = a,b,c,d
In [8]: e
Out[8]:
array([[ 0. 0. 0. 0.], [ 1. 1. 1. 1.], [ 2. 2. 2. 2.],
[ 3. 3. 3. 3.]], dtype=object)
Modify array e inplace:
In [9]: e += 1
In [10]: e
Out[10]:
array([[ 1. 1. 1. 1.], [ 2. 2. 2. 2.], [ 3. 3. 3. 3.],
[ 4. 4. 4. 4.]], dtype=object)
This did not modify arrays a-d though:
In [11]: a
Out[11]: array([ 0., 0., 0., 0.])
Albeit e[0] was array a prior to the iadd:
In [12]: e[:] = a,b,c,d
In [13]: e[0] is a
Out[13]: True
We can apply a function to the arrays in e, getting array([f(a), f(b),
f(c), f(d)]):
In [14]: np.sum(e)
Out[14]: array([ 6., 6., 6., 6.])
Observe that if e was a 2D array, np.sum(e) would have returned a
scalar, like so:
In [18]: g = np.array((a,b,c,d))
In [19]: g
Out[19]:
array([[ 0., 0., 0., 0.],
[ 1., 1., 1., 1.],
[ 2., 2., 2., 2.],
[ 3., 3., 3., 3.]])
In [20]: np.sum(g)
Out[20]: 24.0
Which means:
We can create an array of arrays, and have numpy broadcast an ufunc to
multiple arrays.
The other obvious way is, as mentioned by others, to keep the arrays in
a normal
Python container (e.g. list) and use a for loop or functional
programming (map,
apply, reduce).
Sturla
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20110913/7bb08dbb/attachment.html>
More information about the NumPy-Discussion
mailing list