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
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 to share