python - 如何按索引拆分数组,其中拆分的子数组包含拆分点

标签 python arrays numpy split stride

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

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

但是 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]])]

最佳答案

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

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]])]

关于python - 如何按索引拆分数组,其中拆分的子数组包含拆分点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54020479/

相关文章:

python - Python 中的 SVM 回归速度更快

python - 如何在django中使用用户身份验证

javascript - Rails 中显示的内容与他们选择的内容不同的自动完成字段

python - Numpy 设置工具 : How to compile fortran file as part of a module

python - 将 C bitfiddling 移植到 Python 的惯用方法

python - 通过 Web API 设置 Hudson 构建描述

c - 应用于数组类型的 sizeof

javascript - jQuery秒表,计算平均值并显示

python - 多进程还是多线程? - 并行化数百万次迭代的简单计算并将结果存储在单个数据结构中

arrays - 如何在 NumPy 中将 HDF5 二维数组转换为一维数组?