w3resource

NumPy: Average of every consecutive triplet of elements of a given array


Average every consecutive triplet in an array.

Write a NumPy program to create an array which is the average of every consecutive triplet of elements in a given array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array
arr1 = np.array([1, 2, 3, 2, 4, 6, 1, 2, 12, 0, -12, 6])

# Displaying the original array
print("Original array:")
print(arr1)

# Reshaping the array into rows with three elements each and computing the mean along the rows (axis=1)
result = np.mean(arr1.reshape(-1, 3), axis=1)

# Displaying the average of every consecutive triplet of elements of the array
print("Average of every consecutive triplet of elements of the said array:")
print(result) 

Sample Output:

Original array:
[  1   2   3   2   4   6   1   2  12   0 -12   6]
Average of every consecutive triplet of elements of the said array:
[ 2.  4.  5. -2.]

Explanation:

In the above code -

  • arr1 = np.array([1,2,3, 2,4,6, 1,2,12, 0,-12,6]): Create a NumPy array 'arr1' with the given values.
  • arr1.reshape(-1, 3): Reshape 'arr1' into a 2D array with 3 columns and an automatically inferred number of rows using -1. In this case, it will result in a 4x3 array.
  • result = np.mean(arr1.reshape(-1, 3), axis=1): Calculate the mean of the reshaped array along axis 1 (row-wise mean).
  • print(result): Finally print() function prints the resulting array containing the row-wise mean values.

Pictorial Presentation:

NumPy: Average of every consecutive triplet of elements of a given array

Python-Numpy Code Editor: