Remove item in list if outside of IQR

I am trying to remove an item from a list if it is outside the interquartile range from the median.

Here's a list:

l = [69, 70, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 87, 89]

      

IQR, median and above and below median, used with import numpy as np

iqr = np.subtract(*np.percentile(l, [75, 25]))
median = np.percentile(l, 50)
minus = median - iqr
plus = median + iqr

      

Minus number is 69 and plus number is 71 (using IQR above and below median)

However, when iterating over the list and removing items (87, 89) that are above / below iqr. They are not removed from the list.

for i in l:
    if i < minus:
        del i
    if i > plus:
        del i

      

When I print the list, it still shows 87, 89.

+3


source to share


3 answers


for  ele in l[:]:
    if ele < minus or ele > plus:
        l.remove(ele)

      



You have to make a copy of l l[:]

and modify the actual list itself usingl.remove

+1


source


del

is not the operator you are looking for. It is used to remove a reference to an object and is thus useful for garbage collection.

You are probably looking for:



import numpy as np
l = [69, 70, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 87, 89]
iqr = np.subtract(*np.percentile(l, [75, 25]))
median = np.percentile(l, 50)
minus = median - iqr
plus = median + iqr

arr = np.array(l)
arr[ (minus < arr) & (arr < plus)]

      

+1


source


just convert it to numpy array and then from there:

l = np.array(l)
l[(l >= 69) & (l <= 71)]

      

what he.

+1


source







All Articles