2012-09-21 46 views
1

我试图从数组中返回一个(方形)节,其中索引环绕着边。我需要处理一些索引,但是它起作用,但是,我希望最后两行代码具有相同的结果,为什么他们不? numpy如何解释最后一行?使用数组的Numpy索引

作为一个额外的问题:我是用这种方法效率低下吗?我使用的是product,因为我需要对范围进行取模,所以它会环绕,否则我会使用a[imin:imax, jmin:jmax, :],当然。

import numpy as np 
from itertools import product 

i = np.arange(-1, 2) % 3 
j = np.arange(1, 4) % 3 

a = np.random.randint(1,10,(3,3,2)) 

print a[i,j,:] 
# Gives 3 entries [(i[0],j[0]), (i[1],j[1]), (i[2],j[2])] 
# This is not what I want... 

indices = list(product(i, j)) 
print indices 

indices = zip(*indices) 

print 'a[indices]\n', a[indices] 
# This works, but when I'm explicit: 
print 'a[indices, :]\n', a[indices, :] 
# Huh? 

回答

3

的问题是,advanced indexing被触发,如果:

选择对象,OBJ,是[...]与至少一种序列对象或ndarray元组

的最简单的修复方法是使用重复索引:

a[i][:, j] 

另一种方法是使用ndarray.take,如果指定mode='wrap'这会为您执行模操作:

a.take(np.arange(-1, 2), axis=0, mode='wrap').take(np.arange(1, 4), axis=1, mode='wrap') 
3

为了让先进的索引是在那么我看来product更好的解决方案的另一种方法。

如果你对每一个维度的整数数组这些广播一起输出作为广播形状相同的输出(你会明白我的意思)......

i, j = np.ix_(i,j) # this adds extra empty axes 

print i,j 

print a[i,j] 
# and now you will actually *not* be surprised: 
print a[i,j,:] 

注意,这是一个3x3x2阵列,而你有一个9x2阵列,但简单的重塑会解决这个问题,3x3x2阵列实际上更接近你想要的。

其实惊喜仍然隐藏的方式,因为在你的例子a[indices]相同​​但a[indicies,:]a[(indicies[0], indicies[1]),:]这是不是一个巨大的惊喜,这是不同的。请注意,a[indicies[0], indicies[1],:]确实会给出相同的结果。