次のようなものを変換するnumpy関数はありますか:
[0, 1, 0, 1, 1, 1, 0, 1, 1]
次のように、連続する範囲の開始/終了ペアの配列に:
[[1, 2],
[3, 6],
[7, 9]]
残念ながら、私は numpy をインストールしていませんが、このロジックがそれを行うはずです。
import itertools
x = [0, 1, 0, 1, 1, 1, 0, 1, 1]
# get the indices where 1->0 and 0->1
diff = np.diff(x)
diff_index = diff.nonzero(x)
# pair up the ranges using itertools
def pairwise(iterable):
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
ranges = pairwise(x)
ドキュメンテーション:
def find_starts_ends(x):
temp = [0]
temp.extend(x)
temp.append(0)
diffs = np.diff(temp)
ends = np.where(diffs == -1)[0]
starts = np.where(diffs == 1)[0]
return np.vstack((starts, ends)).T
結果:
>>> find_starts_ends(a)
array([[1, 2],
[3, 6],
[7, 9]])
>>> find_starts_ends([1,1,0,0,1,1])
array([[0, 2],
[4, 6]])