我正在使用python和numpy。我正在使用 n 維陣列。我想選擇所有帶有索引的元素
arr[a,b,:,c]
但我希望能夠像引數一樣選擇切片位置。例如,如果引數
#pos =2
arr[a,b,:,c]
#pos =1
arr[a,:,b,c]
uj5u.com熱心網友回復:
numpy.moveaxis(array,pos,0)我會用[ 1 ]將感興趣的軸(在 pos 處)移到前面,然后簡單地用[:,a,b,c].
還有numpy.take[ 2 ],但在您的情況下,您仍然需要遍歷每個維度 a、b、c,所以我認為 moveaxis 更方便。也許有一種更直接的方法可以做到這一點。
uj5u.com熱心網友回復:
在嘗試切片之前,您可以根據自己的喜好np.transpose排列陣列,因為您將感興趣的軸(即)“移到后面”。這樣,您可以重新排列st ,您可以隨時呼叫。僅包含and的示例:arr:arrarr[a,b,c]ab
import numpy as np
a = 0
b = 2
target_axis = 1
# Generate some random data
arr = np.random.randint(10, size=[3, 3, 3], dtype=int)
print(arr)
#[[[0 8 2]
# [3 9 4]
# [0 3 6]]
#
# [[8 5 4]
# [9 8 5]
# [8 6 1]]
#
# [[2 2 5]
# [5 3 3]
# [9 1 8]]]
# Define transpose s.t. target_axis is the last axis
transposed_shape = np.arange(arr.ndim)
transposed_shape = np.delete(transposed_shape, target_axis)
transposed_shape = np.append(transposed_shape, target_axis)
print(transposed_shape)
#[0 2 1]
# Caution! These 0 and 2 above do not come from a or b.
# Instead they are the indices of the axes.
# Transpose arr
arr_T = np.transpose(arr, transposed_shape)
print(arr_T)
#[[[0 3 0]
# [8 9 3]
# [2 4 6]]
#
# [[8 9 8]
# [5 8 6]
# [4 5 1]]
#
# [[2 5 9]
# [2 3 1]
# [5 3 8]]]
print(arr_T[a,b])
#[2 4 6]
uj5u.com熱心網友回復:
將切片軸移動到一端的想法是一個很好的想法。各種 numpy 函式都使用了這個想法。
In [171]: arr = np.ones((2,3,4,5),int)
In [172]: arr[0,0,:,0].shape
Out[172]: (4,)
In [173]: arr[0,:,0,0].shape
Out[173]: (3,)
另一個想法是建立一個索引元組:
In [176]: idx = (0,0,slice(None),0)
In [177]: arr[idx].shape
Out[177]: (4,)
In [178]: idx = (0,slice(None),0,0)
In [179]: arr[idx].shape
Out[179]: (3,)
要以編程方式執行此操作,可能更容易從可以修改的串列或陣列開始,然后將其轉換為元組以進行索引。詳細資訊將根據您更喜歡指定軸和變數的方式而有所不同。
如果其中任何一個a,b,c是陣列(或串列),您可能會得到一些形狀上的驚喜,因為這是混合高級和基本索引的情況。但只要它們是標量,這不是問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461725.html
