【问题标题】:Numpy indexing using array使用数组的 Numpy 索引
【发布时间】:2012-09-21 23:37:32
【问题描述】:

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

【问题讨论】:

    标签: multidimensional-array numpy


    【解决方案1】:

    问题是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')
    

    【讨论】:

      【解决方案2】:

      提供另一种在我看来比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 数组,但简单的 reshape 将解决这个问题,并且 3x3x2 数组实际上可能更接近您想要的。

      实际上,惊喜仍然以某种方式隐藏,因为在您的示例中,a[indices]a[indices[0], indicies[1]] 相同,但 a[indicies,:]a[(indicies[0], indicies[1]),:],这并不奇怪它不同。请注意,a[indicies[0], indicies[1],:] 确实给出了相同的结果。

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2017-06-24
          • 2018-01-22
          • 2023-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多