拆分多个值的numpy数组?

时间:2012-08-01 20:33:06

标签: python arrays numpy split

根据我的问题 Fastest way to approximately compare values in large numpy arrays? 我正在寻找各种方法来分割我想要的阵列。我有一个排序数组(2D,按一列中的值排序),并希望将其拆分为多个数组。基于索引的长度不等,但值的范围相等。我发现的最接近的问题是 Split array at value in numpy 但是我想做点不同的事情。说我有(一维例子):

[0.1, 3.5, 6.5, 7.9, 11.4, 12.0, 22.3, 24.5, 26.7, 29.9]

我想把它分成范围[0,10] [10,20] [20,30]所以它变成了

[0.1, 3.5, 6.5, 7.9] [11.4, 12.0] [22.3, 24.5, 26.7, 29.9]

1 个答案:

答案 0 :(得分:6)

1d案例可以像这样完成

>>> A = np.array([0.1, 3.5, 6.5, 7.9, 11.4, 12.0, 22.3, 24.5, 26.7, 29.9])
>>> split_at = A.searchsorted([10, 20])
>>> B = numpy.split(A, split_at)

如果我理解你的问题,这也适用于2d,例如:

>>> A = array([[  0.1,   0. ],
               [  3.5,   1. ],
               [  6.5,   2. ],
               [  7.9,   3. ],
               [ 11.4,   4. ],
               [ 12. ,   5. ],
               [ 22.3,   6. ],
               [ 24.5,   7. ],
               [ 26.7,   8. ],
               [ 29.9,   9. ]])
>>> split_at = A[:, 0].searchsorted([10, 20])
>>> B = numpy.split(A, split_at)
>>> B
[array([[ 0.1,  0. ],
       [ 3.5,  1. ],
       [ 6.5,  2. ],
       [ 7.9,  3. ]]),
 array([[ 11.4,   4. ],
       [ 12. ,   5. ]]),
 array([[ 22.3,   6. ],
       [ 24.5,   7. ],
       [ 26.7,   8. ],
       [ 29.9,   9. ]])]