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:
JavaScript
x
8
1
list= [1,1,1,1,1,2,2,2,2,3,3,3,4,4,5]
2
3
for i in range(0,len(list)):
4
if list[i] == list[i-1]:
5
list[i] = list[i-1] = np.nan
6
7
Out: [nan, nan, nan, nan, 1, nan, nan, nan, nan, nan, nan, 3, nan, nan, 5]
8
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:
JavaScript
1
2
1
Out: [nan, nan, nan, nan, nan, nan, nan, nan, nan, 3, 3, 3, 4, 4, 5]
2
Advertisement
Answer
Use Counter
to keep track of elements in list and use list comprehension
with condition
JavaScript
1
9
1
import numpy as np
2
from collections import Counter
3
4
list1 = [1,1,1,1,1,2,2,2,2,3,3,3,4,4,5]
5
counter = Counter(list1)
6
7
list_new = [np.nan if counter[i] > 3 else i for i in list1]
8
print(list_new)
9
Output:
JavaScript
1
2
1
[nan, nan, nan, nan, nan, nan, nan, nan, nan, 3, 3, 3, 4, 4, 5]
2
Alternate solution
JavaScript
1
12
12
1
from itertools import groupby
2
b = [(k, sum(1 for i in g)) for k,g in groupby(list1)]
3
4
list2 = []
5
for i,j in b:
6
if j > 3:
7
list2.extend([np.nan]*j)
8
else:
9
list2.extend([i]*j)
10
11
print(list2)
12
Output:
JavaScript
1
2
1
[nan, nan, nan, nan, nan, nan, nan, nan, nan, 3, 3, 3, 4, 4, 5, 3]
2