w3resource

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

NumPy: Array Object Exercise-202 with Solution

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:

Previous: Write a NumPy program to create a 90x30 array filled with random point numbers, increase the number of items (10 edge elements) shown by the print statement.
Next: Write a NumPy program to create a 11x3 array filled with student information (id, class and name) and shuffle the said array rows starting from 3rd to 9th.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-202.php