【问题标题】:Get element from array based on list of indices根据索引列表从数组中获取元素
【发布时间】:2021-05-13 13:57:35
【问题描述】:
z = np.arange(15).reshape(3,5)
indexx = [0,2]
indexy = [1,2,3,4]

zz = []
for i in indexx:
  for j in indexy:
    zz.append(z[i][j])

输出:

zz >> [1, 2, 3, 4, 11, 12, 13, 14]

这实际上使数组变平,但只保留两个索引列表中存在索引的元素。

这可行,但对于较大的数组/索引列表来说非常慢。有没有办法使用 numpy 加快速度?

谢谢。

已编辑以显示所需的输出。

【问题讨论】:

    标签: python python-3.x list numpy indexing


    【解决方案1】:

    整数列表可用于访问 numpy 数组感兴趣的条目。

    z[indexx][:,indexy].flatten()
    

    【讨论】:

      【解决方案2】:
      x = {"apple", "banana", "cherry"}
      y = {"google", "microsoft", "apple"}
      
      z = x.intersection(y) 
      
      print(z)
      
      z => apples
      

      如果我理解正确,请使用 Python 集。然后将其投射到列表中。

      【讨论】:

        【解决方案3】:

        同时在多个维度中建立索引需要broadcasting 索引彼此相对。 np.ix_ 是一个方便的工具:

        In [127]: z
        Out[127]: 
        array([[ 0,  1,  2,  3,  4],
               [ 5,  6,  7,  8,  9],
               [10, 11, 12, 13, 14]])
        In [128]: z[np.ix_(indexx, indexy)]
        Out[128]: 
        array([[ 1,  2,  3,  4],
               [11, 12, 13, 14]])
        

        将其转换为 1d 是一项微不足道的 ravel() 任务。

        查看ix_ 产生的结果,这里是 (2,1) 和 (1,4) 数组。您可以“从头开始”构造这样的数组:

        In [129]: np.ix_(indexx, indexy)
        Out[129]: 
        (array([[0],
                [2]]),
         array([[1, 2, 3, 4]]))
        

        【讨论】:

          猜你喜欢
          • 2021-05-13
          • 1970-01-01
          • 2022-10-14
          • 1970-01-01
          • 2012-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多