How to Compute the Average of a 2D Array in Python?

Estimated read time 1 min read

To compute the average of a 2D array in Python, you can use the NumPy library. Here’s an example:

import numpy as np

# Define a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Compute the average
average = np.mean(array_2d)

print("Average:", average)

In this example, the NumPy library is imported to work with arrays and numerical operations. The array_2d variable is defined as a NumPy array representing the 2D array. The np.mean() function is then used to compute the average of all the elements in the 2D array. The resulting average is stored in the average variable and printed.

Make sure to have NumPy installed (pip install numpy) before running this code. The np.mean() function computes the average of all the elements in the array, treating the 2D array as a flattened 1D array. If you want to compute the average along a specific axis (e.g., row-wise or column-wise), you can specify the axis parameter of the np.mean() function accordingly.

Feel free to adapt the code based on your specific 2D array and requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply