NumPy: Calculate average values of two given numpy arrays
NumPy: Array Object Exercise-158 with Solution
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:
Python-Numpy Code Editor:
Previous: Write a NumPy program to create a new array which is the average of every consecutive triplet of elements of a given array.
Next: Write a NumPy program to rearrange columns of a given numpy 2D array using given index positions.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/python-exercises/numpy/python-numpy-exercise-158.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics