简体   繁体   English

如何将列表中相等的连续数字替换为nan?

[英]How to replace equal consecutive numbers in a list to nan?

I'm trying to replace equal consecutive numbers in a list to nan.我正在尝试将列表中相等的连续数字替换为 nan。 I having problems to replace all values when there is a odd number of equal consecutive numbers.当有奇数个相等的连续数字时,我无法替换所有值。

This is my code, very simple:这是我的代码,非常简单:

list= [1,1,1,1,1,2,2,2,2,3,3,3,4,4,5]

for i in range(0,len(list)):
    if list[i] == list[i-1]:
    list[i] = list[i-1] = np.nan

Out: [nan, nan, nan, nan, 1, nan, nan, nan, nan, nan, nan, 3, nan, nan, 5]

Another question, if I want to replace only those values that repeated more than 3 times, for example the numbers 1 or 2 that are repeated 5 and 4 times respectively.另一个问题,如果我只想替换那些重复超过 3 次的值,例如分别重复 5 次和 4 次的数字 1 或 2。

This is what I want:这就是我要的:

Out: [nan, nan, nan, nan, nan, nan, nan, nan, nan, 3, 3, 3, 4, 4, 5]

Use Counter to keep track of elements in list and use list comprehension with condition使用Counter跟踪列表中的元素并使用条件list comprehension

import numpy as np
from collections import Counter

list1 = [1,1,1,1,1,2,2,2,2,3,3,3,4,4,5]
counter = Counter(list1)

list_new = [np.nan if counter[i] > 3 else i for i in list1]
print(list_new)

Output: Output:

[nan, nan, nan, nan, nan, nan, nan, nan, nan, 3, 3, 3, 4, 4, 5]

Alternate solution替代解决方案

from itertools import groupby
b = [(k, sum(1 for i in g)) for k,g in groupby(list1)]

list2 = []
for i,j in b:
    if j > 3:
        list2.extend([np.nan]*j)
    else:
        list2.extend([i]*j)

print(list2)

Output: Output:

[nan, nan, nan, nan, nan, nan, nan, nan, nan, 3, 3, 3, 4, 4, 5, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM