pythonnumpyaveragemeanstandard-deviation

Calculate average between mean and 1st standard deviation


I have an array:

import numpy as np

# Create an array of values
values = np.array([41,17,44,36,14,29,33,38,49,39,22,15,46])

# Calculate the mean
mean = np.mean(values)

# Calculate the standard deviation
standard_deviation = np.std(values)

How can I calculate the average of values between mean and the 1st standard deviation? I have:

# Calculate the average of values between the mean and the first standard deviation
mean_between_mean_and_first_standard_deviation = np.mean(values[(values >= mean) & (values <= standard_deviation)])
print("Average between mean and first standard deviation:", mean_between_mean_and_first_standard_deviation)

I get:

Average between mean and first standard deviation: nan

std


Solution

  • The following graphic should make it clearer. You need to select values that are between mean and mean plus one times the standard_deviation.

    np.mean(values[(values >= mean) & (values < (mean + 1 * standard_deviation))])
    

    Or if you want mid-point, you could do:

    np.mean([mean, mean + 1 * standard_deviation])
    

    enter image description here