Help us understand the problem. What is going on with this article?

# リスト内包表記を使わずにnumpy.arrayの行or列に関数を適用する

More than 3 years have passed since last update.

# やりたいこと

```>>> def dobule(x):
...     print(x)
...     return x * 2
...
>>> A = np.arange(6).reshape((3,2))
>>> A
array([[0, 1],
[2, 3],
[4, 5]])
```

```>>> np.array([double(a) for a in A])
[0 1]
[2 3]
[4 5]
array([[ 0,  2],
[ 4,  6],
[ 8, 10]])
```

for文を使わないで済む方法を考えたい。

# 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]])
```

（要素数は6つなのに何で7回printされてるんだろう？）

`numpy.vectorize`だと要素ごとに関数を適用することになり、

# 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]])
```

`numpy.apply_along_axis`を使えば行or列単位で関数を適用することができる。

Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away