【问题标题】:Split a large numpy array into separate arrays with a list of grouped indices将大型 numpy 数组拆分为具有分组索引列表的单独数组
【发布时间】:2015-10-21 06:31:17
【问题描述】:

给定 2 个数组:一个用于主数据集,第二个作为引用主数据集的分组索引列表。我正在寻找从给定索引数据生成新数组的最快方法?

这是我目前从双键列表生成 2 个数组的解决方案:

# Lets make a large point cloud with 1 million entries and a list of random paired indices
import numpy as np
COUNT = 1000000
POINT_CLOUD = np.random.rand(COUNT,3) * 100
INDICES = (np.random.rand(COUNT,2)*COUNT).astype(int)  # (1,10),(233,12),...

# Split into sublists, np.squeeze is needed here because i don't want arrays of single elements.
LIST1 = POINT_CLOUD[np.squeeze(INDICES[:,[0]])]
LIST2 = POINT_CLOUD[np.squeeze(INDICES[:,[1]])]

这行得通,但它有点慢,而且它只适用于生成 2 个列表,如果有一个可以处理任何大小的索引组的解决方案(例如:((1,2,3,4) ,(8,4,5,3),...)

类似:

# PSEUDO CODE using quadruple keys
INDICES = (np.random.rand(COUNT,4)*COUNT).astype(int)
SPLIT = POINT_CLOUD[<some pythonic magic>[INDICES]]
SPLIT[0] = np.array([points from INDEX #1])
SPLIT[1] = np.array([points from INDEX #2])
SPLIT[2] = np.array([points from INDEX #3])
SPLIT[3] = np.array([points from INDEX #4])

【问题讨论】:

    标签: python-2.7 numpy


    【解决方案1】:

    你只需要重塑索引数组:

    >>> result = POINT_CLOUD[INDICES.T]
    >>> np.allclose(result[0], LIST1)
    True
    >>> np.allclose(result[1], LIST2)
    True
    

    如果你知道子数组的数量你也可以解包列表

    >>> result.shape
    (2, 1000000, 3)
    >>> L1, L2 = result
    >>> np.allclose(L1, LIST1)
    True
    >>> # etc
    

    这适用于较大的索引组。对于您问题中的第二个示例:

    >>> INDICES = (np.random.rand(COUNT,4)*COUNT).astype(int)
    >>> SPLIT = POINT_CLOUD[INDICES.T]
    >>> SPLIT.shape
    (4, 1000000, 3)
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多