假设我有一个带有一些任意值的矩阵A:
array([[ 2, 4, 5, 3],
[ 1, 6, 8, 9],
[ 8, 7, 0, 2]])
Run Code Online (Sandbox Code Playgroud)
并且矩阵B包含A中元素的索引:
array([[0, 0, 1, 2],
[0, 3, 2, 1],
[3, 2, 1, 0]])
Run Code Online (Sandbox Code Playgroud)
我该如何选择值一个被指出乙,即:
A[B] = [[2, 2, 4, 5],
[1, 9, 8, 6],
[2, 0, 7, 8]]
Run Code Online (Sandbox Code Playgroud) 使用沿给定维度的(n-1)维数组访问n维数组的最优雅方法是什么,如虚拟示例中所示
a = np.random.random_sample((3,4,4))
b = np.random.random_sample((3,4,4))
idx = np.argmax(a, axis=0)
Run Code Online (Sandbox Code Playgroud)
我现在如何访问idx a以获得最大值,a就像我使用过一样a.max(axis=0)?或者如何检索idxin中指定的值b?
我想过使用,np.meshgrid但我认为这是一种矫枉过正.请注意,尺寸axis可以是任何有用的轴(0,1,2),并且事先不知道.有一种优雅的方式来做到这一点?
我试图让索引按最后一个轴排序一个多维数组,例如
>>> a = np.array([[3,1,2],[8,9,2]])
Run Code Online (Sandbox Code Playgroud)
我想要这样的指数i,
>>> a[i]
array([[1, 2, 3],
[2, 8, 9]])
Run Code Online (Sandbox Code Playgroud)
根据numpy.argsort的文档,我认为它应该这样做,但我收到错误:
>>> a[np.argsort(a)]
IndexError: index 2 is out of bounds for axis 0 with size 2
Run Code Online (Sandbox Code Playgroud)
编辑:我需要以相同的方式重新排列相同形状的其他数组(例如,b这样的数组a.shape == b.shape)......这样
>>> b = np.array([[0,5,4],[3,9,1]])
>>> b[i]
array([[5,4,0],
[9,3,1]])
Run Code Online (Sandbox Code Playgroud) 当我们具有一维numpy数组时,可以按以下方式对其进行排序:
>>> temp = np.random.randint(1,10, 10)
>>> temp
array([5, 1, 1, 9, 5, 2, 8, 7, 3, 9])
>>> sort_inds = np.argsort(temp)
>>> sort_inds
array([1, 2, 5, 8, 0, 4, 7, 6, 3, 9], dtype=int64)
>>> temp[sort_inds]
array([1, 1, 2, 3, 5, 5, 7, 8, 9, 9])
Run Code Online (Sandbox Code Playgroud)
注意:我知道我可以使用np.sort; 显然,我需要其他数组的排序索引-这只是一个简单的示例。现在我们可以继续我的实际问题。
我试图对2D数组应用相同的方法:
>>> d = np.random.randint(1,10,(5,10))
>>> d
array([[1, 6, 8, 4, 4, 4, 4, 4, 4, 8],
[3, 6, 1, 4, 5, 5, 2, 1, 8, 2],
[1, …Run Code Online (Sandbox Code Playgroud)