Home > Enterprise >  Finding the mean of all values within a range in an array
Finding the mean of all values within a range in an array

Time:02-21

I have an array:

flux = np.array(folded2_lc_binned.flux.value, dtype = 'float')

which gives me the following results:

flux = [0.99996269 1.0000602  1.00017059 1.00002182 1.00007594 0.9999696
 1.00011313 1.00012934 1.00005817 0.99997538 0.99956554 0.99896783
 0.99861592 0.99828523 0.99859077 0.9990297  0.9994933  0.99997085
 1.00000501 0.999919   1.00013363 1.00007749 1.00005972 1.00003064
 0.99999666 1.00003886 1.00002563 1.00004816]

How can I calculate the mean (average) of the array, but only including the values between 0.999 and 1.001?

CodePudding user response:

You can filter the elements on the condition that they're between 0.999 and 1.001, and then use .mean():

import numpy as np

flux = np.array([0.99996269, 1.0000602,  1.00017059, 1.00002182, 1.00007594, 0.9999696,
 1.00011313, 1.00012934, 1.00005817, 0.99997538, 0.99956554, 0.99896783,
 0.99861592, 0.99828523, 0.99859077, 0.9990297,  0.9994933,  0.99997085,
 1.00000501, 0.999919,   1.00013363, 1.00007749, 1.00005972, 1.00003064,
 0.99999666, 1.00003886, 1.00002563, 1.00004816])

print((flux[(0.999 <= flux) & (flux <= 1.001)]).mean())

CodePudding user response:

Can you a list comprenhension like this?

import statistics
statistics.mean([float(data) for data in flux if data and 0.999 < float(data) < 1.001])

CodePudding user response:

You could also use Statistics library and line comprehension as follows:

import statistics

flux = [0.99996269, 1.0000602,  1.00017059, 1.00002182, 1.00007594, 0.9999696,
 1.00011313, 1.00012934, 1.00005817, 0.99997538, 0.99956554, 0.99896783,
 0.99861592, 0.99828523, 0.99859077, 0.9990297,  0.9994933,  0.99997085,
 1.00000501, 0.999919,  1.00013363, 1.00007749, 1.00005972, 1.00003064,
 0.99999666, 1.00003886, 1.00002563, 1.00004816]

mean_lst = statistics.mean([i for i in flux if i >= 0.999 and i <= 1.001])
print(mean_lst)

This would give you the output:

0.9999554604166667
  • Related