代码之家  ›  专栏  ›  技术社区  ›  Mattijn

如何按包含拆分点的拆分子数组的索引拆分数组

  •  2
  • Mattijn  · 技术社区  · 7 年前

    我有一个包含值的二维数组和一个包含索引值的一维数组,我想在其中拆分二维矩阵,其中拆分的子数组包括“拆分点”。

    我知道我可以用 numpy.split 按索引拆分的函数,我知道我可以使用 stride_tricks 拆分数组以创建连续重叠的子集视图。

    但似乎 stride_ticks 仅当我们要将数组拆分为大小相等的子数组时才适用。

    最小示例,我可以执行以下操作:

    >>> import numpy as np
    >>> array = np.random.randint(0,10, (10,2))
    >>> indices = np.array([2,3,8])
    >>> array
    array([[8, 1],
           [1, 0],
           [2, 0],
           [8, 8],
           [1, 6],
           [7, 8],
           [4, 4],
           [9, 4],
           [6, 7],
           [6, 4]])
    
    >>> split_array = np.split(array, indices, axis=0)
    >>> split_array
    [array([[8, 1],
            [1, 0]]), 
    
     array([[2, 0]]), 
    
     array([[8, 8],
            [1, 6],
            [7, 8],
            [4, 4],
            [9, 4]]), 
    
     array([[6, 7],
            [6, 4]])]
    

    但我只是想在 split 我可以定义的函数 include_split_point=True 这将给我一个这样的结果:

    [array([[8, 1],
            [1, 0],
            [2, 0]]), 
    
     array([[2, 0],
            [8, 8]]), 
    
     array([[8, 8],
            [1, 6],
            [7, 8],
            [4, 4],
            [9, 4],
            [6, 7]]), 
    
     array([[6, 7],
            [6, 4]])]
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Ernest S Kirubakaran    7 年前

    创建索引元素重复的新数组

    new_indices = np.zeros(array.shape[0], dtype = int)
    new_indices[indices] = 1
    new_indices += 1
    new_array = np.repeat(array, new_indices, axis = 0)
    

    更新索引以说明更改的数组

    indices = indices + np.arange(1, len(indices)+1)
    

    像往常一样使用索引拆分

    np.split(new_array, indices, axis = 0)
    

    输出:

    [array([[8, 1],
            [1, 0],
            [2, 0]]), 
     array([[2, 0],
            [8, 8]]), 
     array([[8, 8],
            [1, 6],
            [7, 8],
            [4, 4],
            [9, 4],
            [6, 7]]), 
     array([[6, 7],
            [6, 4]])]
    
    推荐文章