8

我将 Python 与numpy.

我有一个 numpy 索引数组a

>>> a
array([[5, 7],
       [12, 18],
       [20, 29]])
>>> type(a)
<type 'numpy.ndarray'>

我有一个 numpy 索引数组b

>>> b
array([[2, 4],
       [8, 11],
       [33, 35]])
>>> type(b)
<type 'numpy.ndarray'>

我需要a用一个数组加入一个数组b

a+ b=>[2, 4] [5, 7] [8, 11] [12, 18] [20, 29] [33, 35]

=>a并且b有索引数组 => [2, 18] [20, 29] [33, 35]

(索引([2, 4][5, 7][8, 11][12, 18])按顺序排列

=> 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18=> [2, 18])

对于这个例子:

>>> out_c
array([[2, 18],
       [20, 29],
       [33, 35]])

有人可以建议,我怎么得到out_c

更新:@Geoff 建议解决方案python union of multiple range。这个解决方案是否是大型数据阵列中最快和最好的?

4

3 回答 3

5

(新答案)使用 Numpy

ranges = np.vstack((a,b))
ranges.sort(0)

# List of non-overlapping ranges
nonoverlapping = (ranges[1:,0] - ranges[:-1,1] > 1).nonzero()[0]

# Starts are 0, and all the starts not overlapped by their predecessor
starts = np.hstack(([0], nonoverlapping + 1))

# Ends are -1 and all the ends who aren't overlapped by their successor
ends = np.hstack(( nonoverlapping, [-1]))

# Result
result = np.vstack((ranges[starts, 0], ranges[ends, 1])).T

(旧答案)使用列表和集合

import numpy as np
import itertools

def ranges(s):
    """ Converts a list of integers into start, end pairs """
    for a, b in itertools.groupby(enumerate(s), lambda(x, y): y - x):
        b = list(b)
        yield b[0][1], b[-1][1]

def intersect(*args):
    """ Converts any number of numpy arrays containing start, end pairs 
        into a set of indexes """
    s = set()
    for start, end in np.vstack(args):
        s = s | set(range(start,end+1))
    return s

a = np.array([[5,7],[12, 18],[20,29]])
b = np.array([[2,4],[8,11],[33,35]])

result = np.array(list(ranges(intersect(a,b))))

参考

于 2013-04-03T13:36:12.167 回答
3

不漂亮,但它有效。我不喜欢最后的循环,buy想不出没有它的方法:

ab = np.vstack((a,b))
ab.sort(axis=0)

join_with_next = ab[1:, 0] - ab[:-1, 1] <= 1
endpoints = np.concatenate(([0],
                            np.where(np.diff(join_with_next) == True)[0]  + 2,
                            [len(ab,)]))
lengths = np.diff(endpoints)
new_lengths = lengths.copy()
if join_with_next[0] == True:
    new_lengths[::2] = 1
else:
    new_lengths[1::2] = 1
new_endpoints = np.concatenate(([0], np.cumsum(new_lengths)))
print endpoints, lengths
print new_endpoints, new_lengths

starts = endpoints[:-1]
ends = endpoints[1:]
new_starts = new_endpoints[:-1]
new_ends = new_endpoints[1:]
c = np.empty((new_endpoints[-1], 2), dtype=ab.dtype)

for j, (s,e,ns,ne) in enumerate(zip(starts, ends, new_starts, new_ends)):
    if e-s != ne-ns:
        c[ns:ne] = np.array([np.min(ab[s:e, 0]), np.max(ab[s:e, 1])])
    else:
        c[ns:ne] = ab[s:e]

>>> c
array([[ 2, 18],
       [20, 29],
       [33, 35]])
于 2013-04-03T15:56:55.227 回答
1

也许您可以尝试使用 numpy.concatenate() 将数组连接在一起,然后找到每行的最小值和最大值……然后将 c 创建为每行的最小值和最大值的矩阵。

或者,np.minimum 和 np.maximum 比较两个数组并找到最小值和最大值,因此您可以找到每行的最小值和最大值,然后将其分配给矩阵 c。

于 2013-04-03T13:26:01.503 回答