w3resource

NumPy: Calculate average values of two given numpy arrays


Calculate average values of two arrays.

Write a NumPy program to calculate the average values of two given NumPy arrays.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating two Python lists representing arrays
array1 = [[0, 1], [2, 3]]
array2 = [[4, 5], [0, 3]]

# Displaying the original arrays
print("Original arrays:")
print(array1)
print(array2)

# Calculating the average values of the two arrays element-wise and storing the result
result = (np.array(array1) + np.array(array2)) / 2

# Displaying the average values of the two arrays
print("Average values of two said NumPy arrays:")
print(result) 

Sample Output:

Original arrays:
[[0, 1], [2, 3]]
[[4, 5], [0, 3]]
Average values of two said numpy arrays:
[[2. 3.]
 [1. 3.]]

Explanation:

In the above exercise we first define two arrays ‘array1’ and ‘array2’ with given values.

result = (np.array(array1) + np.array(array2)) / 2

In the above code -

  • np.array(array1) + np.array(array2): This code convert both lists into NumPy arrays and perform element-wise addition. This results in a new NumPy array where each element is the sum of the corresponding elements in the original arrays.
  • (np.array(array1) + np.array(array2)) / 2: Divide the sum of the arrays by 2 to calculate the element-wise average.
  • Store the resulting NumPy array containing the element-wise average values in the variable ‘result’.

Pictorial Presentation:

NumPy: Calculate average values of two given numpy arrays

For more Practice: Solve these Related Problems:

  • Write a NumPy program to compute the element-wise average of two matrices and verify the output dimensions.
  • Create a function that takes two arrays and returns a new array representing their arithmetic mean.
  • Implement a solution that uses np.mean on the stack of two arrays along a new axis to compute the average.
  • Test the average calculation on arrays with different data types and validate type consistency in the result.

Go to:


PREV : Average every consecutive triplet in an array.
NEXT : Rearrange columns of a 2D array using indices.


Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.