yong jie
yong jie

Reputation: 73

How to filter out a list by majority in python?

I am currently working on a algorithm where it takes value from a ultrasonic sensor(distance sensor) which is constantly reading and calculating the average of the last 10 taken value. The problem is with the ultrasonic sensor will have random spikes which will significantly throw off the average reading

example of readings

19.42
19.43
130.50
19.46
19.44
19.42
144.52
19.4
145.90
19.37
[Average Distance:23] #just a example not actual results

so now I am wondering if there is any method to disregard the high value base on majority, say if the list has a majority of small values it will ignore the high value and vice versa, if there are majority of high values ignore small values.

example of desired result

19.42
19.43
130.50  
19.46
19.44
19.42
144.52
19.4
145.90
19.37
[Average Distance:19]  #ignored spiked values are the majority of numbers are 19

Do let me know if Further explanation/examples are needed, thank you in advance.

Upvotes: 0

Views: 56

Answers (1)

piterbarg
piterbarg

Reputation: 8219

you can use numpy.median:

import numpy as np
vals = np.array([19.42
,19.43
,130.50  
,19.46
,19.44
,19.42
,144.52
,19.4
,145.90
,19.37])
np.median(vals)

produces 19.435. Median is a point such that half the observations are above and half are below, see median

Upvotes: 1

Related Questions