簡體   English   中英

如何在 NumPy 數組中查找連續元素組

[英]How to find the groups of consecutive elements in a NumPy array

我必須對 NumPy 數組中的連續元素進行聚類。 考慮以下示例

a = [ 0, 47, 48, 49, 50, 97, 98, 99]

輸出應該是一個元組列表,如下所示

[(0), (47, 48, 49, 50), (97, 98, 99)]

這里的差異只是元素之間的差異。 如果差異也可以指定為限制或硬編碼數字,那就太好了。

def consecutive(data, stepsize=1):
    return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)

a = np.array([0, 47, 48, 49, 50, 97, 98, 99])
consecutive(a)

產量

[array([0]), array([47, 48, 49, 50]), array([97, 98, 99])]

這是一個小函數,可能會有所幫助:

def group_consecutives(vals, step=1):
    """Return list of consecutive lists of numbers from vals (number list)."""
    run = []
    result = [run]
    expect = None
    for v in vals:
        if (v == expect) or (expect is None):
            run.append(v)
        else:
            run = [v]
            result.append(run)
        expect = v + step
    return result

>>> group_consecutives(a)
[[0], [47, 48, 49, 50], [97, 98, 99]]
>>> group_consecutives(a, step=47)
[[0, 47], [48], [49], [50, 97], [98], [99]]

PS這是純Python。 對於 NumPy 解決方案,請參閱 unutbu 的答案。

(a[1:]-a[:-1])==1將產生一個布爾數組,其中False表示運行中斷。 您還可以使用內置的numpy.grad

這就是我到目前為止的想法:不確定是否 100% 正確

import numpy as np
a = np.array([ 0, 47, 48, 49, 50, 97, 98, 99])
print np.split(a, np.cumsum( np.where(a[1:] - a[:-1] > 1) )+1)

返回:

>>>[array([0]), array([47, 48, 49, 50]), array([97, 98, 99])]

測試一維數組

找到差異不是一個的地方

diffs = numpy.diff(array) != 1

獲取 diff 的索引,獲取第一個維度並添加一個,因為diff與前一個索引進行比較

indexes = numpy.nonzero(diffs)[0] + 1

用給定的索引拆分

groups = numpy.split(array, indexes)

這聽起來有點像家庭作業,所以如果你不介意我會建議一個方法

您可以使用遍歷列表

for i in range(len(a)):
    print a[i]

您可以測試列表中的下一個元素是否滿足以下條件

if a[i] == a[i] + 1:
    print "it must be a consecutive run"

您可以將結果單獨存儲在

results = []

當心 - 上面隱藏了一個索引超出范圍的錯誤,您需要處理

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM