在布尔值重复n次的点拆分列表

2024-05-08 20:02:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表,其中有一个时间序列的时间和值。有一个包含布尔值的对应列表,用于标识时间序列中NAN值的位置。我需要做的是,如果一个真值(即NAN值)重复超过5次(一行中有6个NAN值),则将列表拆分为两个(在序列的开始和结束处,因此在两个结果列表中没有NAN值)。所以基本上,我需要把这个列表分成一个更小的列表,从一个包含6个以上重复NAN值的间隔开始和结束。我尝试了一些类似的方法:

    for i in range(len(nan_list)-5):
        if nan_list[i] == True and nan_list[i+1] == True and nan_list[i+2] == True and nan_list[i+3] == True and nan_list[i+4] == True and nan_list[i+5] == True:

我不确定从现在开始最好的办法是什么,我肯定还有更好的办法。你知道吗

然后,我需要做的是,对于重复次数少于5次的重复NAN值(一行中有6个NAN值),将这些值替换为使用scipy中的b样条计算的值。我不太清楚该怎么办。谢谢!你知道吗


Tags: and方法intrue列表for间隔时间
1条回答
网友
1楼 · 发布于 2024-05-08 20:02:42

如果我理解的正确,那么您希望基于另一个列表的索引(假设具有相同长度的列表)拆分一个列表,这样其他列表中的n重复元素就可以定义切片应该出现的位置。一个“优雅的”,但不是最有效的方法是只遍历其他列表的n大小的片段,检查当前索引处是否有all(nan_list[i:i+n])如果是,将索引之前的第一个列表中的所有内容作为片段放入结果中,然后跳过n位置并重复该过程。不过,我更喜欢程序性方法:

def split_list(source, nan_data, nan_len=6):
    result = []  # a list for our final result
    last_pos = 0  # holds the last sliced position
    counter = 0  # a counter for sequential NaNs
    for i, is_nan in enumerate(nan_data):
        if not is_nan:  # encountered a non-NaN, check how many consecutive NaNs we had
            if counter >= nan_len:  # we have a match...
                result.append(source[last_pos:i-counter])  # add a new slice to our result
                last_pos = i  # set the new slice position
            counter = 0  # reset the counter
        else:
            counter += 1  # NaN found, increase the counter
    # find the last slice, if any
    left_over = source[last_pos:] if counter < nan_len else source[last_pos:-counter]
    if left_over:
        result.append(left_over)
    return result  # return the result

然后,您可以使用它根据nan_len列表中连续的True值(或计算为True的任何值)拆分任何source列表,例如:

base_list = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
             "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"]
nan_list = [True, False, True, False, True, True, True, True, True, True,
            False, True, False, True, True, False, True, True, True, False]

print(split_list(base_list, nan_list, 3))
# [['01', '02', '03', '04'], ['11', '12', '13', '14', '15', '16'], ['20']]

相关问题 更多 >