>>> def dobule(x):
... print(x)
... return x * 2
...
>>> A = np.arange(6).reshape((3,2))
>>> A
array([[0, 1],
[2, 3],
[4, 5]])
Consider how to apply your own function in rows or columns of ʻA`.
>>> np.array([double(a) for a in A])
[0 1]
[2 3]
[4 5]
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])
This can be achieved by using list comprehension as above, I want to think of a way to avoid using a for statement.
numpy.vectorize
https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html
>>> import numpy as np
>>> np.vectorize(double)(A)
0
0
1
2
3
4
5
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])
(Why is it printed 7 times even though the number of elements is 6?)
With numpy.vectorize
, the function will be applied element by element,
It cannot be applied on a row or column basis.
numpy.apply_along_axis
https://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html
>>> np.apply_along_axis(double, 0, A)
[0 2 4]
[1 3 5]
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])
>>> np.apply_along_axis(double, 1, A)
[0 1]
[2 3]
[4 5]
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])
You can use numpy.apply_along_axis
to apply a function on a row or column basis.
Recommended Posts