1

我试图从数组中返回一个(方形)部分,其中索引环绕边缘。我需要处理一些索引,但是它可以工作,但是,我希望最后两行代码具有相同的结果,为什么不呢?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?
4

3 回答 3

4

问题是在以下情况下会触发高级索引:

选择对象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')
于 2012-09-21T12:41:25.963 回答
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 数组实际上可能更接近您想要的。

Actually the surprise is still hidden in a way, because in your examples a[indices] is the same as a[indices[0], indicies[1]] but a[indicies,:] is a[(indicies[0], indicies[1]),:] which is not a big surprise that it is different. Note that a[indicies[0], indicies[1],:] does give the same result.

于 2012-09-21T12:46:30.520 回答
1

请参阅:http ://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing

添加时:,您将混合整数索引和切片。这些规则非常复杂,并且比我在上面的链接中解释得更好。

于 2012-09-21T12:24:23.380 回答