Skip to content
Advertisement

How to replace equal consecutive numbers in a list to nan?

I’m trying to replace equal consecutive numbers in a list to 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.

This is what I want:

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

Advertisement

Answer

Use Counter to keep track of elements in list and use list comprehension with condition

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:

[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:

[nan, nan, nan, nan, nan, nan, nan, nan, nan, 3, 3, 3, 4, 4, 5, 3]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement