python - 在 numpy 数组中找到一段 Trues

标签 python arrays numpy boolean

有没有一种好方法可以在 numpy boolean 数组中找到一段 True?如果我有一个像这样的数组:

x = numpy.array([True,True,False,True,True,False,False])

我可以得到一个索引数组吗:

starts = [0,3]
ends = [1,4]

或任何其他适当的方式来存储此信息。我知道这可以通过一些复杂的 while 循环来完成,但我正在寻找更好的方法。

最佳答案

您可以用 False 填充 x(一个在开头,一个在结尾),然后使用 np.diff . “diff”为 1 表示从 False 到 True 的转换,-1 表示从 True 到 False 的转换。

惯例是将范围的结尾表示为最后一个 之后的索引。此示例符合约定(您可以轻松使用 ends-1 而不是 ends 来获取问题中的数组):

x1 = np.hstack([ [False], x, [False] ])  # padding
d = np.diff(x1.astype(int))
starts = np.where(d == 1)[0]
ends = np.where(d == -1)[0]
starts, ends
=> (array([0, 3]), array([2, 5]))

关于python - 在 numpy 数组中找到一段 Trues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29853322/

相关文章:

python - Pandas - 根据条件计算相关事件

javascript - 用于渲染 HTML 和 javascript 的 Python 库

python - 连接数据帧时处理极坐标中的空列

c - C中while循环中的数组

python - 执行矩阵乘法时出现内存错误

python - 组合步骤

python - Python/Pygame 中的矩形旋转

python - bs4.FeatureNotFound : Couldn't find a tree builder with the features you requested: html5lib

arrays - 如何使用 typescript 的字符串索引接口(interface)?

c - 如何将C中的字符转换为字符数组?