1
1

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 3 years have passed since last update.

[Python numpy] 配列のインデックスを動的に指定する

Last updated at Posted at 2020-05-20

単語帳.毎回検索するのが面倒なので転載多め.元URLあり.

方法1: take(indices, axis=)メソッド

indicesは配列でもOK.
しかしaxisにタプルを入れて複数の次元を指定することは不可.

nx, ny, nz = 2, 3, 4
arr = np.arange(nx * ny * nz).reshape(nx, ny, nz)

arr.take(0, axis=0) # arr[0]と同じ
arr.take(1, axis=1) # arr[:,1]と同じ

[Numpy: numpy.take]
(https://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html)

方法2: sline(None)を組み合わせる

slice(None),またはslice(None, None, None)はインデックスでいう:と同じ.

# 以下はarr[:,0,2]と同じ
I = [slice(None)] * arr.ndim # [:,:,:]と同じ
I[1] = 0
I[2] = 2
arr[tuple(I)]

[stackoverflow: Dynamic axis indexing of Numpy ndarray]
(https://stackoverflow.com/questions/31094641/dynamic-axis-indexing-of-numpy-ndarray)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?