Jose Luis Landivar S
Jose Luis Landivar S

Reputation: 170

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

Upvotes: 0

Views: 253

Answers (2)

d.b
d.b

Reputation: 32548

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

Upvotes: 3

Yakov Dan
Yakov Dan

Reputation: 3357

For example, you could do this:

np.mean(values[np.logical_and(values >= mean, values <= mean+standard_deviation)])

values >= mean evaluates to a boolean array of the same shape as values such that it has True everywhere the condition is satisfied and False otherwise. Similarly, for values <= mean+standard_deviation.

What remains is to find where both conditions are satisfied using np.logical_and(). This boolean array is then used to compute the mean of values only at such indices where the values satisfy both conditions

Upvotes: 1

Related Questions