Python:设置下限和上限,将它们从数组中移除,并计算新数组的平均值

Python: set lower- and upperbounds, remove them from array, and calculate the mean of new array

enter image description here

我需要帮助来解决这个问题!我对编码还很陌生 python。 我在 print 语句中设置了我的上限和下限为 25 和 15,然后我尝试定义 2 行,删除超过上限的数字低于下限 每次我 运行 代码,我都会得到错误:

"return umr_any(a, axis, dtype, out, keepdims)

TypeError: only integer scalar arrays can be converted to a scalar index"

我知道可能有更简单的方法来解决它,我很想知道!但我也希望这段代码能够工作,因为我觉得我可以从中学到很多东西! 提前谢谢你!

代码如下:

import math 
import numpy as np
    
def fermentationRate(measuredRate, lowerBound, upperBound):
        def remove_values_from_list1(measuredRate, lowerBound):
            return [value for value in measuredRate if value < lowerBound]
    
        def remove_values_from_list2(measuredRate, upperbound):
            return [value for value in measuredRate if value > upperBound]
        x = np.array([measuredRate]) 
        for i in range(len(measuredRate)):
            if (x.any(x[i]) < lowerBound) and (x.any(x[i]) > upperBound):
                measuredRate = remove_values_from_list1(measuredrate,lowerBound)
                measuredRate = remove_values_from_list2(measuredrate,upperBound)
                averageRate = np.mean(measuredRate)
            else:
                averageRate = np.mean(measuredRate)
        return averageRate
    print(fermentationRate(np.array([20.1, 19.3, 1.1, 18.2, 19.7, 121.1, 20.3, 20.0]), 15, 25))

由于 measuredRate 是一个 numpy 数组,您不需要遍历它来找到满足某些条件的位置。

def fermentationRate(measuredRate, lowerBound, upperBound):
    # Create logical arrays containing True or False for both conditions
    condition1 = measuredRate >= lowerBound 
    condition2 = measuredRate <= upperBound 
    # logical_and the two: select the row if both conditions are true
    select_row = np.logical_and(condition1, condition2)
    filtered_array = measuredRate[select_row]
    return filtered_array.mean()

一旦你理解了这一点,就可以将它浓缩成一行,尽管它的可读性要差得多:

def fermentationRate(measuredRate, lowerBound, upperBound):
    return measuredRate[
               np.logical_and(measuredRate >= lowerBound, 
                              measuredRate <= upperBound)
           ].mean()