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:
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:
For more Practice: Solve these Related Problems:
- Write a NumPy program to compute the element-wise average of two matrices and verify the output dimensions.
- Create a function that takes two arrays and returns a new array representing their arithmetic mean.
- Implement a solution that uses np.mean on the stack of two arrays along a new axis to compute the average.
- Test the average calculation on arrays with different data types and validate type consistency in the result.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics