[PYTHON] Apply functions to rows or columns of numpy.array without using list comprehensions

Thing you want to do

>>> 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

Apply functions to rows or columns of numpy.array without using list comprehensions
Use numpy to remove columns or rows that contain elements of certain conditions
List of activation functions (2020)
EP 7 Use List Comprehensions Instead of map and filter
Python list comprehensions and generators
Python higher-order functions and comprehensions
Python tuple comprehensions and generator expressions
Apply functions to rows or columns of numpy.array without using list comprehensions
Python comprehension (list and generator expressions) [additional]
About PyQt signal, connect and lambda expressions
List of frequently used built-in functions and methods
filter, map, reduce with js and python (There are also arrow expressions, lambda expressions, comprehension expressions)
[Python] How to delete rows and columns in a table (list of drop method options)
List of libraries to install when installing Python using Pyenv
I tried to get the index of the list using the enumerate function
ABC170 E --How to solve without using multiset of Smart Infants
I tried to get a list of AMI Names using Boto3