23
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

多次元np.arrayでmapをする

Posted at

多次元配列の場合

>>> a = [[3,2,1],[5,4,6]]
>>> [*map(lambda x: sorted(x), a)]
[[1, 2, 3], [4, 5, 6]]

普通にやるだけです。

np.arrayの場合

np.vectorizeは一次元配列の場合mapのように動きますが、多次元の場合、最小の一要素を見ていくようで、ダメです。

>>> a = np.array([[3,2,1],[5,4,6]])
>>> np.vectorize(lambda x: sorted(x))(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/numpy/1.14.3_1/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2755, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "/usr/local/Cellar/numpy/1.14.3_1/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2825, in _vectorize_call
    ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
  File "/usr/local/Cellar/numpy/1.14.3_1/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2785, in _get_ufunc_and_otypes
    outputs = func(*inputs)
  File "<stdin>", line 1, in <lambda>
TypeError: 'numpy.int64' object is not iterable

np.apply_along_axisを使いましょう。

>>> a = np.array([[3,2,1],[5,4,6]])
>>> np.apply_along_axis(lambda x: sorted(x), 1, a)
array([[1, 2, 3],
       [4, 5, 6]])
23
15
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?