gpt4 book ai didi

python - 单步索引与两步索引时的 Numpy 3D 数组转置

转载 作者:太空狗 更新时间:2023-10-30 00:02:09 26 4
gpt4 key购买 nike

import numpy as np
x = np.random.randn(2, 3, 4)
mask = np.array([1, 0, 1, 0], dtype=np.bool)
y = x[0, :, mask]
z = x[0, :, :][:, mask]
print(y)
print(z)
print(y.T)

为什么上面的分两步操作会变成一步操作的转置?

最佳答案

这是列表索引的相同行为:

In [87]: x=np.arange(2*3*4).reshape(2,3,4)
In [88]: x[0,:,[0,2]]
Out[88]:
array([[ 0, 4, 8],
[ 2, 6, 10]])
In [89]: x[0,:,:][:,[0,2]]
Out[89]:
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])

在第二种情况下,x[0,:,:] 返回一个 (3,4) 数组,下一个索引选择 2 列。

在第一种情况下,它首先选择第一个和最后一个维度,然后附加切片(中间维度)。 0[0,2] 产生一个 2 维度,并附加从中间开始的 3,给出 (2,3) 形状。

这是混合基本索引和高级索引的情况。

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that.

这不是一个容易理解或解释的案例。基本上对于最终维度应该是什么存在一些歧义。它试图用一个示例 x[:,ind_1,:,ind_2] 来说明,其中 ind_1ind_2 是 3d(或一起广播到那个).

较早的解释是:

How does numpy order array slice indices?

Combining slicing and broadcasted indexing for multi-dimensional numpy arrays

===========================

解决这个问题的方法是用一个数组——一个列向量来代替切片

In [221]: x[0,np.array([0,1,2])[:,None],[0,2]]
Out[221]:
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])
In [222]: np.ix_([0],[0,1,2],[0,2])
Out[222]:
(array([[[0]]]), array([[[0],
[1],
[2]]]), array([[[0, 2]]]))
In [223]: x[np.ix_([0],[0,1,2],[0,2])]
Out[223]:
array([[[ 0, 2],
[ 4, 6],
[ 8, 10]]])

尽管最后一个例子是 3d,(1,3,2)。 ix_ 不喜欢标量 0。另一种使用 ix_ 的方法:

In [224]: i,j=np.ix_([0,1,2],[0,2])
In [225]: x[0,i,j]
Out[225]:
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])

这里有一种获取相同数字的方法,但在 (2,1,3) 数组中:

In [232]: i,j=np.ix_([0,2],[0])
In [233]: x[j,:,i]
Out[233]:
array([[[ 0, 4, 8]],

[[ 2, 6, 10]]])

关于python - 单步索引与两步索引时的 Numpy 3D 数组转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35016092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com