私は取る方法を知っていますx[:,:,:,:,j,:]
(これは次元4のj番目のスライスを取ります)。
ディメンションが実行時に既知であり、既知の定数ではない場合、同じことを行う方法はありますか?
そのための1つのオプションは、プログラムでスライスを作成することです。
slicing = (slice(None),) * 4 + (j,) + (slice(None),)
numpy.take()
別の方法は、またはを使用することndarray.take()
です。
>>> a = numpy.array([[1, 2], [3, 4]])
>>> a.take((1,), axis=0)
array([[3, 4]])
>>> a.take((1,), axis=1)
array([[2],
[4]])
次のように、 slice関数を使用して、実行時に適切な変数リストを使用して呼び出すことができます。
# Store the variables that represent the slice in a list/tuple
# Make a slice with the unzipped tuple using the slice() command
# Use the slice on your array
例:
>>> from numpy import *
>>> a = (1, 2, 3)
>>> b = arange(27).reshape(3, 3, 3)
>>> s = slice(*a)
>>> b[s]
array([[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]])
これは次と同じです:
>>> b[1:2:3]
array([[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]])
最後に:
、通常の表記で2の間に何も指定しないのと同じことNone
は、作成するタプルのそれらの場所に配置することです。
実行時にすべてが決定された場合は、次のことができます。
# Define the data (this could be measured at runtime)
data_shape = (3, 5, 7, 11, 13)
print('data_shape = {}'.format(data_shape))
# Pick which index to slice from which dimension (could also be decided at runtime)
slice_dim = len(data_shape)/2
slice_index = data_shape[slice_dim]/2
print('slice_dim = {} (data_shape[{}] = {}), slice_index = {}'.format(slice_dim, slice_dim, data_shape[slice_dim], slice_index))
# Make a data set for testing
data = arange(product(data_shape)).reshape(*data_shape)
# Slice the data
s = [slice_index if a == slice_dim else slice(None) for a in range(len(data_shape))]
d = data[s]
print('shape(data[s]) = {}, s = {}'.format(shape(d), s))
これはよりも長くなりますndarray.take()
がslice_index = None
、配列の次元が非常に少なく、実際にはスライスしたくない場合のように、機能します(ただし、先にスライスしたくないかどうかはわかりません)。時間の)。
省略記号を使用して、繰り返しコロンを置き換えることもできます。Pythonで省略記号のスライス構文をどのように使用しますか?の回答を参照してください。例として。