9951 explained code solutions for 126 technologies


python-scipyHow do I calculate the average of a numpy array in Python?


To calculate the average of a numpy array in Python, you can use the mean() function. This function takes in an array as an argument and returns the average of all the values in the array. The following example code shows how to use the mean() function to calculate the average of a numpy array.

import numpy as np

# Create a numpy array
a = np.array([1, 2, 3, 4, 5])

# Calculate the average
average = np.mean(a)

# Print the average
print(average)

# Output
3.0

The code above consists of the following parts:

  1. Importing the numpy library as np - This allows us to access the mean() function.
  2. Creating a numpy array - This is the array whose average we want to calculate.
  3. Calculating the average - This is done by calling the mean() function and passing in the array as an argument.
  4. Printing the average - This prints the average of the array.

For more information, see the Numpy Documentation.

Edit this code on GitHub