Hy everybody, I'm wondering what is the (best) way to apply the same function to multiple arrays.
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.])
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.])
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.