我在理解多维数组的numpy索引时遇到了很多麻烦。在我正在使用的这个例子中,假设我有一个二维数组A,它是100x10。然后我有另一个数组B,它是一个0到9之间的100x1 1D值的数组(A的索引)。在MATLAB中,我会用A(sub2ind(size(A), 1:size(A,1)', B)
来换取的每一行,存储B的相应行中Numpy索引行为
所以索引处的值,作为一个测试案例,让我们说我有这样的:
A = np.random.rand(100,10)
B = np.int32(np.floor(np.random.rand(100)*10))
如果我打印它们的形状,我得到:
print A.shape returns (100L, 10L)
print B.shape returns (100L,)
当我尝试指标分为A采用B天真的(错误地)
Test1 = A[:,B]
print Test1.shape returns (100L, 100L)
但如果我做
Test2 = A[range(A.shape[0]),B]
print Test2.shape returns (100L,)
这就是我想要的。我无法理解这里所做的区分。在我看来,A [:,5]和A [范围(A.shape [0]),5]应该返回相同的东西,但它不在这里。 :
与使用range(sizeArray)
有什么不同,它只是从[0:sizeArray]中创建一个数组来使用索引?
可能重复[改变numpy数组与索引数组](http://stackoverflow.com/questions/30379663/changing-numpy-array-with-array-of- index) – shx2
尝试使用'np.arange(A.shape [0])[:,None]'作为第一个索引。 – hpaulj