7

私は取る方法を知っていますx[:,:,:,:,j,:](これは次元4のj番目のスライスを取ります)。

ディメンションが実行時に既知であり、既知の定数ではない場合、同じことを行う方法はありますか?

4

4 に答える 4

10

そのための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]])
于 2012-06-28T16:58:11.580 に答える
7

次のように、 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は、作成するタプルのそれらの場所に配置することです。

于 2012-06-28T17:01:07.467 に答える
1

実行時にすべてが決定された場合は、次のことができます。

# 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、配列の次元が非常に少なく、実際にはスライスしたくない場合のように、機能します(ただし、先にスライスしたくないかどうかはわかりません)。時間の)。

于 2018-04-12T18:11:35.547 に答える
0

省略記号を使用して、繰り返しコロンを置き換えることもできます。Pythonで省略記号のスライス構文をどのように使用しますか?の回答を参照してください。例として。

于 2012-09-16T03:18:46.440 に答える