Python 3.x 简化numpy表达式
我如何简化这一点:Python 3.x 简化numpy表达式,python-3.x,numpy,multidimensional-array,Python 3.x,Numpy,Multidimensional Array,我如何简化这一点: import numpy as np ex = np.arange(27).reshape(3, 3, 3) def get_plane(axe, index): return ex.swapaxes(axe, 0)[index] # is there a better way ? 我找不到一个numpy函数来获得高维数组中的平面,有吗 编辑 ex.take(index,axis=axe)方法很好,但是它复制了数组,而不是我最初想要的视图 那么,索引(无需复
import numpy as np
ex = np.arange(27).reshape(3, 3, 3)
def get_plane(axe, index):
return ex.swapaxes(axe, 0)[index] # is there a better way ?
我找不到一个numpy函数来获得高维数组中的平面,有吗
编辑
ex.take(index,axis=axe)
方法很好,但是它复制了数组,而不是我最初想要的视图
那么,索引(无需复制)第n维数组以获取其二维切片的最短方法是什么呢?索引和轴受此启发,您可以执行以下操作:
def get_plane(axe, index):
slices = [slice(None)]*len(ex.shape)
slices[axe]=index
return ex[tuple(slices)]
get_plane(1,1)
输出:
array([[ 3, 4, 5],
[12, 13, 14],
[21, 22, 23]])
你说的“飞机”是什么意思
In [16]: ex = np.arange(27).reshape(3, 3, 3)
平面、行和列等名称是任意约定,在numpy中没有正式定义。此数组的默认显示类似于3个“平面”或“块”,每个都有行和列:
In [17]: ex
Out[17]:
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
标准索引允许我们查看任意尺寸的任意二维块:
In [18]: ex[0]
Out[18]:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [19]: ex[0,:,:]
Out[19]:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [20]: ex[:,0,:]
Out[20]:
array([[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20]])
In [21]: ex[:,:,0]
Out[21]:
array([[ 0, 3, 6],
[ 9, 12, 15],
[18, 21, 24]])
有很多种方式可以说我想要维度1中的块0等,但是首先要确保您理解这个索引。这是numpy的核心功能
In [23]: np.take(ex, 0, 1)
Out[23]:
array([[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20]])
In [24]: idx = (slice(None), 0, slice(None)) # also np.s_[:,0,:]
In [25]: ex[idx]
Out[25]:
array([[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20]])
是的,你可以交换轴(或转置),这符合你的需要。认为你在寻找
np.take
:np.take(ex,index,axis=axe)
。很好的回答:这是很容易理解的,它提供了数组的视图,而不是复制,比如np.take