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?
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:
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With