另一个子集一个numpy数组

时间:2016-03-01 00:45:21

标签: python arrays numpy indexing

在基本级别,我可以将一个numpy数组索引为另一个,这样我就可以返回一个数组的索引,这样:

a = [1,2,3,4,5,6]

b = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

和0.6的索引可以通过以下方式找到:

c = a[b==0.6]

然而,现在我有3D阵列,而且我无法理解我的需求。

我有3个阵列:

A = [[21,22,23....48,49,50]] # An index over the range 20-50 with shape (1,30)

B = [[0.1,0.6,0.5,0.4,0.8...0.7,0.2,0.4],
     ..................................
     [0.5,0.2,0.7,0.1,0.5...0.8,0.9,0.3]] # This is my data with shape (40000, 30)

C = [[0.8],........[0.9]] # Maximum values from each array in B with shape (40000,1)

我想通过索引数据(B)中每个数组中的最大值(C)来了解位置(来自A)

我试过了:

D = A[B==C]

但我一直收到错误:

IndexError: index 1 is out of bounds for axis 0 with size 1

我自己可以得到:

B==C # prints as arrays of True or False

但我无法从A中检索索引位置。

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?使用argmax函数获取每行最大值的索引,并使用索引获取A中的相应值。

In [16]: x = np.random.random((20, 30))
In [16]: max_inds = x.argmax(axis=1)

In [17]: max_inds.shape
Out[17]: (20,)

In [18]: A = np.arange(x.shape[1])

In [19]: A.shape
Out[19]: (30,)

In [20]: A[max_inds]
Out[20]: 
array([20,  5, 27, 19, 27, 21, 18, 25, 10, 24, 16, 21,  6,  7, 27, 17, 24,
        8, 27,  8])