求数组中某个范围内所有值的平均值



我有一个数组:

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

这给了我以下结果:

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]

如何计算数组的平均值,但仅包括0.999和1.001之间的值?

您可以在元素位于0.9991.001之间的条件下过滤元素,然后使用.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())

你能得到这样的列表压缩吗?

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

您还可以使用统计库和行理解,如下所示:

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)

这会给你输出:

0.9999554604166667

最新更新