组numpy的成多个子阵列使用的值的数组

Bry*_*ank 5 numpy

我有沿着线点的数组:

a = np.array([18, 56, 32, 75, 55, 55])
Run Code Online (Sandbox Code Playgroud)

我有另一个数组对应于我想用来访问一个信息的索引(他们总是具有相等的长度)。数组a和数组b均未排序。

b = np.array([0, 2, 3, 2, 2, 2])
Run Code Online (Sandbox Code Playgroud)

我想组a分成多个子阵列,使得下面将是可能的:

c[0] -> array([18])
c[2] -> array([56, 75, 55, 55])
c[3] -> array([32])
Run Code Online (Sandbox Code Playgroud)

虽然上述的例子是简单的,我将处理数百万个点,因此有效的方法是优选的。此外,还必须晚些时候点中的任意子阵列可以以这种方式在以后通过自动方法程序访问。

Div*_*kar 5

这是一种方法 -

def groupby(a, b):
    # Get argsort indices, to be used to sort a and b in the next steps
    sidx = b.argsort(kind='mergesort')
    a_sorted = a[sidx]
    b_sorted = b[sidx]

    # Get the group limit indices (start, stop of groups)
    cut_idx = np.flatnonzero(np.r_[True,b_sorted[1:] != b_sorted[:-1],True])

    # Split input array with those start, stop ones
    out = [a_sorted[i:j] for i,j in zip(cut_idx[:-1],cut_idx[1:])]
    return out
Run Code Online (Sandbox Code Playgroud)

一种更简单但效率较低的方法是使用np.split替换最后几行并获取输出,如下所示 -

out = np.split(a_sorted, np.flatnonzero(b_sorted[1:] != b_sorted[:-1])+1 )
Run Code Online (Sandbox Code Playgroud)

样本运行 -

In [38]: a
Out[38]: array([18, 56, 32, 75, 55, 55])

In [39]: b
Out[39]: array([0, 2, 3, 2, 2, 2])

In [40]: groupby(a, b)
Out[40]: [array([18]), array([56, 75, 55, 55]), array([32])]
Run Code Online (Sandbox Code Playgroud)

要获取覆盖整个 ID 范围的子数组b-

def groupby_perID(a, b):
    # Get argsort indices, to be used to sort a and b in the next steps
    sidx = b.argsort(kind='mergesort')
    a_sorted = a[sidx]
    b_sorted = b[sidx]

    # Get the group limit indices (start, stop of groups)
    cut_idx = np.flatnonzero(np.r_[True,b_sorted[1:] != b_sorted[:-1],True])

    # Create cut indices for all unique IDs in b
    n = b_sorted[-1]+2
    cut_idxe = np.full(n, cut_idx[-1], dtype=int)

    insert_idx = b_sorted[cut_idx[:-1]]
    cut_idxe[insert_idx] = cut_idx[:-1]
    cut_idxe = np.minimum.accumulate(cut_idxe[::-1])[::-1]

    # Split input array with those start, stop ones
    out = [a_sorted[i:j] for i,j in zip(cut_idxe[:-1],cut_idxe[1:])]
    return out
Run Code Online (Sandbox Code Playgroud)

样本运行 -

In [241]: a
Out[241]: array([18, 56, 32, 75, 55, 55])

In [242]: b
Out[242]: array([0, 2, 3, 2, 2, 2])

In [243]: groupby_perID(a, b)
Out[243]: [array([18]), array([], dtype=int64), 
           array([56, 75, 55, 55]), array([32])]
Run Code Online (Sandbox Code Playgroud)

  • @berkelem 保持元素在“a”中的顺序。使用默认值时,无法保证这一点。 (2认同)