@chthonicdaemon的回答让你完成了90%的工作,但如果你想使用索引来切分数组,你需要一些额外的信息。假设你想使用这些索引来提取数组中不为0的区域。你已经找到了数组变化的索引,但你不知道这种变化是从True到False还是相反。因此,你需要检查第一个和最后一个值并进行相应的调整。否则,在某些情况下,你将提取零段而不是数据。
例如:
import numpy as np
def contiguous_regions(condition):
"""Finds contiguous True regions of the 1D boolean array "condition".
Returns a 2D array where the first column is the start index of the region
and the second column is the end index."""
idx = np.flatnonzero(np.diff(condition)) + 1
if condition[0]:
idx = np.append(0, idx)
if condition[-1]:
idx = np.append(idx, len(condition))
return idx.reshape(-1, 2)
t = np.linspace(0, 4*np.pi, 20)
x = np.abs(np.sin(t)) + 0.1
x[np.sin(t) < 0.5] = 0
print x
for start, stop in contiguous_regions(x != 0):
print x[start:stop]
在这种情况下,我们的示例数据集如下所示:
array([ 0. , 0.71421271, 1.06940027, 1.01577333, 0. ,
0. , 0. , 0. , 0. , 0. ,
0. , 0.93716648, 1.09658449, 0.83572391, 0. ,
0. , 0. , 0. , 0. , 0. ])
并通过以下方式实现:
for start, stop in contiguous_regions(x != 0):
print x[start:stop]
我们将获得:
[ 0.71421271 1.06940027 1.01577333]
[ 0.93716648 1.09658449 0.83572391]
A
是如何使用的吗?例如:A = np.array([1, 2, 3])
,并且你期望得到的输出结果是什么?答案可能涉及到np.diff
或者np.ediff1d
。 - YXD