5
4

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.

Numpyのarrayで複数の要素を取り出す

Last updated at Posted at 2014-05-21

連続していない要素を取り出したい時が多々ある

>>> a = np.array([1,2,3,4])
>>> indices = [0,2]
>>> a[indices]
array([1,3])

要素の入れ替えをしたい時とかに便利

>>> a = np.array([1,2,3,4])
>>> indices = [0,1,3,2]
>>> a[indices]
array([1, 2, 4, 3])

listじゃなくてsetを渡すとエラーに成ったり予期しない挙動をしたりするので注意が必要。特に多次元配列を使う時は注意。

>>> a = np.array([[1,2,3],[3,4,5],[5,6,7]])
>>> a
array([[1, 2, 3],
       [3, 4, 5],
       [5, 6, 7]])
>>> indices = [0,2]
>>> a[indices]
array([[1, 2, 3],
       [5, 6, 7]])
>>> indices = (0,2)
>>> a[indices]
3
5
4
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?