【问题标题】:Indexing a numpy array with a list of tuples用元组列表索引一个 numpy 数组
【发布时间】:2015-04-14 00:01:21
【问题描述】:

为什么我不能像这样使用元组索引列表来索引 ndarray?

idx = [(x1, y1), ... (xn, yn)]
X[idx]

相反,我必须做一些笨拙的事情

idx2 = numpy.array(idx)
X[idx2[:, 0], idx2[:, 1]] # or more generally:
X[tuple(numpy.vsplit(idx2.T, 1)[0])]

有没有更简单、更 Pythonic 的方式?

【问题讨论】:

    标签: numpy multidimensional-array indices


    【解决方案1】:

    您可以使用元组列表,但约定与您想要的不同。 numpy 需要一个行索引列表,后跟一个列值列表。显然,您想要指定 (x,y) 对的列表。

    http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing 文档中的相关部分是“整数数组索引”。


    这是一个示例,在二维数组中寻找 3 个点。 (2d 中的 2 点可能会令人困惑):

    In [223]: idx
    Out[223]: [(0, 1, 1), (2, 3, 0)]
    In [224]: X[idx]
    Out[224]: array([2, 7, 4])
    

    使用您的 xy 索引对样式:

    In [230]: idx1 = [(0,2),(1,3),(1,0)]
    In [231]: [X[i] for i in idx1]
    Out[231]: [2, 7, 4]
    
    In [240]: X[tuple(np.array(idx1).T)]
    Out[240]: array([2, 7, 4])
    

    X[tuple(zip(*idx1))] 是另一种转换方式。 tuple() 在 Python2 中是可选的。 zip(*...) 是一个 Python 习惯用法,用于反转列表列表的嵌套。

    你在正确的轨道上:

    In [242]: idx2=np.array(idx1)
    In [243]: X[idx2[:,0], idx2[:,1]]
    Out[243]: array([2, 7, 4])
    

    我的tuple() 只是更紧凑一点(不一定更“pythonic”)。鉴于numpy 约定,某种转换是必要的。

    (我们应该检查 n 维和 m 点的工作原理吗?)

    【讨论】:

      【解决方案2】:

      使用NumPy 数组的元组,可以直接传递给你的数组索引:

      index = tuple(np.array(list(zip(*index_tuple))))
      new_array = list(prev_array[index])
      

      【讨论】:

      • 其实不需要转数组,tuple(zip(*index_tuple))就够了
      猜你喜欢
      • 2018-10-25
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 2018-05-29
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多