numpy数组被不规则对(开始,停止)

时间:2018-10-11 15:16:21

标签: python pandas numpy

我有一个numpy数组,其点值为xy。我有另一个数组,其中包含成对的起始索引和结束索引。最初,此数据以熊猫DataFrame为单位,但是由于它超过6000万,因此loc算法非常慢。有没有numpy的快速方法来拆分呢?

import numpy as np
xy_array = np.arange(100).reshape(2,-1)
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
        17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
        34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
        67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
        84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])

split_paris = [[0, 10], [10, 13], [13, 17], [20, 22]]

expected_result = [
    [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]],
    [[10, 11, 12], [60, 61, 62]],
    [[13, 14, 15, 16], [63, 64, 65, 66]],
    [[20, 21], [70, 71]]
]

更新: 并非总是如此,下一对将从上一个结束开始。

2 个答案:

答案 0 :(得分:1)

您始终可以使用numpy提供的np.array_split函数。并使用您想要的范围

x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]

答案 1 :(得分:1)

这可以做到:

import numpy as np

xy_array = np.array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
                      17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
                      34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
                     [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
                      67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
                      84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])

split_paris = [[0, 10], [10, 13], [13, 17]]

expected_result = [xy_array[:, x:y] for x, y in split_paris]

expected_result
#[array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
#       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]), array([[10, 11, 12],
#       [60, 61, 62]]), array([[13, 14, 15, 16],
#       [63, 64, 65, 66]])]

它使用index slicing基本上是在array[rows, columns]的意义上使:占据了所有行,而x:y占据了从xy的列。