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

Python-Numpy Code Editor: