w3resource

NumPy: Calculate the arithmetic means of corresponding elements of two given arrays of same size


Compute element-wise arithmetic mean of two arrays.

Write a NumPy program to calculate the arithmetic means of corresponding elements of two given arrays of same size.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating two NumPy arrays
nums1 = np.array([[2, 5, 2],
                  [1, 5, 5]])
nums2 = np.array([[5, 3, 4],
                  [3, 2, 5]])

# Displaying Array1
print("Array1:") 
print(nums1)

# Displaying Array2
print("Array2:") 
print(nums2)

# Calculating arithmetic means of corresponding elements of the two arrays
result = np.divide(np.add(nums1, nums2), 2)

# Displaying the arithmetic means of corresponding elements
print("\nArithmetic means of corresponding elements of said two arrays:")
print(result) 

Sample Output:

Array1:
[[2 5 2]
 [1 5 5]]
Array2:
[[5 3 4]
 [3 2 5]]

Arithmetic means of corresponding elements of said two arrays:
[[3.5 4.  3. ]
 [2.  3.5 5. ]]

Explanation:

In the above exercise -

nums1 and nums2 are defined as two 2x3 NumPy arrays with specific values.

print(np.divide(np.add(nums1, nums2), 2))

In the above code -

  • np.add(nums1, nums2) computes the element-wise addition of nums1 and nums2.
  • np.divide(..., 2) takes the result of the element-wise addition and computes the element-wise division by 2.
  • print(...) – Finally print() functionprints the resulting array.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to compute the element-wise mean of two arrays using both direct addition and np.mean with axis=0.
  • Create a function that checks if two arrays have the same shape before computing their arithmetic mean, and raises an error if they do not.
  • Implement a solution that converts integer arrays to float before averaging to preserve decimal precision.
  • Test the arithmetic mean function on arrays with different numerical types and verify the output matches expected values.

Go to:


PREV : Print extended edges of a random 90x30 array.
NEXT : Shuffle specific rows in a 11x3 student data array.


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.