gpt4 book ai didi

python - R/python 向量中的 "grouped/clustered"区域

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:55 24 4
gpt4 key购买 nike

我遇到了以下问题。我想根据以下标准查找带有 1 的“分组/聚集”区域:

从第一个1的位置开始,如果在1之后的窗口中(例如窗口长度==5)没有其他1,则输出的开始和结束位置为1。

  1. 之后的窗口中没有其他 1。

    0 0 0 0 0 1 0 0 0 0 0

开始<- 6

结束<- 6

但是,如果有 1,我想将窗口滑动 1,直到最终窗口中不再有 1。在这种情况下,起始位置将是滑动开始的位置,结束位置将是该区域的最后 1 个位置。

  • 窗口中还有其他 1。
  • 0 0 0 0 0 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0

    开始<- 6

    结束<- 16

    我有很多像这样的向量,其随机分布为 1(除了第一个位置始终为 1)。下面我提供了示例向量和首选输出。我更喜欢用 R 解决这个问题(但 python 也可以)。我非常感谢您的帮助。

    这是基于窗口长度 == 5 的示例:

    数字向量:

    1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 1 1 1 1 0 1 0 1 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1

    (1的位置:1 15 62 63 67 86 252 272 334 335 337 344 348 349 350 357 360 361 362 363 365 367 371 373 391 396 406 410 412)

    输出:

    开始<- 1 15 62 86 252 272 334 344 357 391 406

    结束<- 1 15 67 86 252 272 337 350 373 396 412

    最佳答案

    您可以通过对向量进行游程编码来轻松完成此操作:

    x <- c(1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,1,1,
    1,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
    0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1)

    which(x == 1)
    #[1] 1 15 62 63 67 88 89 91 98 102 103 104 111 114 115 116 117 119 121 125 127 145 150 160 164 166

    window <- 5

    #run length encoding
    y <- rle(x)
    #Run Length Encoding
    # lengths: int [1:37] 1 13 1 46 2 3 1 20 2 1 ...
    # values : num [1:37] 1 0 1 0 1 0 1 0 1 0 ...

    #if run length for zeros is smaller than window replace with 1
    y$values[(y$values == 0) & (y$lengths < window)] <- 1

    #combine runs of ones
    y <- rle(inverse.rle(y))

    start <- cumsum(y$lengths)[y$values == 1] - y$lengths[y$values == 1] + 1
    #[1] 1 15 62 88 98 111 145 160
    end <- cumsum(y$lengths)[y$values == 1]
    #[1] 1 15 67 91 104 127 150 166

    关于python - R/python 向量中的 "grouped/clustered"区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40343813/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com