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.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics