Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy mean with condition

I have algorithm of calculating average speed in pure python:

speed = [...]
avg_speed = 0.0
speed_count = 0

for i in speed:
    if i > 0: # I dont need zeros
        avg_speed += i
        speed_count += 1

if speed_count == 0:
    return 0.0

return avg_speed / speed_count

Is there any way to rewrite this functions with Numpy?

like image 512
Artem Mezhenin Avatar asked Jun 18 '12 14:06

Artem Mezhenin


People also ask

What is NumPy mean and how to use it?

NumPy mean computes the average of the values in a NumPy array. NumPy mean calculates the mean of the values within a NumPy array (or an array-like object). Let’s take a look at a visual representation of this. Imagine we have a NumPy array with six values: We can use the NumPy mean function to compute the mean value:

How to create an array from a condition in NumPy?

In Python, NumPy has a number of library functions to create the array and where is one of them to create an array from the satisfied conditions of another array. The numpy.where () function returns the indices of elements in an input array where the given condition is satisfied. condition : When True, yield x, otherwise yield y.

How do you use multiple conditions in NumPy where ()?

Numpy where () with multiple conditions using logical OR. Numpy where () with multiple conditions using logical AND. Numpy where () with multiple conditions in multiple dimensional arrays. The where () function in NumPy is used for creating a new array from the existing array with multiple numbers of conditions.

What are NumPy’s conditional functions?

Extremely useful for selecting, creating, and managing data, NumPy’s conditional functions are a must for everyone! At the end of this article, you’ll be able to understand and use each one with mastery, improving the quality of your code and your skills. Let’s start! What you’ll learn today? Every function has an example with included output.


2 Answers

I'm surprised no one has suggested the shortest solution:

speeds_np = np.array(speeds)

speeds_np[speeds_np>0].mean()

Explanation:

speedsNp > 0 creates a boolean array of the same size satisfying the (in)equality. If fed into speedsNp, it yields only the corresponding values of speedNp where the value of the boolean array is True. All you need to do then, is just take the mean() of the result.

like image 51
TimY Avatar answered Oct 14 '22 04:10

TimY


The function numpy.average can receive a weights argument, where you can put a boolean array generated from some condition applied to the array itself - in this case, an element being greater than 0:

average_speed = numpy.average(speeds, weights=(speeds > 0))

Hope this helps

like image 28
heltonbiker Avatar answered Oct 14 '22 04:10

heltonbiker