Skip to content
Related Articles

Related Articles

Create an array which is the average of every consecutive subarray of given size using NumPy
  • Last Updated : 02 Sep, 2020

In this article, we will see the program for creating an array of elements in which every element is the average of every consecutive subarrays of size k of a given numpy array of size n such that k is a factor of n i.e. (n%k==0). This task can be done by using numpy.mean() and numpy.reshape() functions together.

Syntax: numpy.mean(arr, axis = None)

Return: Arithmetic mean of the array (a scalar value if axis is none) or array with mean values along specified axis. 

Syntax: numpy_array.reshape(shape)

Return: It returns numpy.ndarray



Example :

Arr = [1,2,3,4,5,6
       7,8,9,10,11
       12,13,14,15,16] 
and K = 2 then 
Output is [ 1.5, 3.5, 5.5, 7.5, 
            9.5, 11.5, 13.5, 15.5].
            
Here, subarray of size k and there average are calculated as :

[1 2]    avg = ( 1 + 2 ) / 2 = 1.5  
[3 4]    avg = ( 3 + 4 ) / 2 = 3.5
[5 6]    avg = ( 5 + 6 ) / 2 = 5.5
[7 8]    avg = ( 7 + 8 ) / 2 = 7.5
[9 10]   avg = ( 9 + 10 ) / 2 = 9.5 
[11 12]  avg = ( 11 + 12 ) / 2 = 11.5 
[13 14]  avg = ( 13 + 14 ) / 2 = 13.5 
[15 16]  avg = ( 15 + 16 ) / 2 = 15.5

Below is the implementation:

Python3




# importing library
import numpy
  
# create numpy array
arr = numpy.array([1, 2, 3, 4, 5,
                   6, 7, 8, 9, 10,
                   11, 12, 13, 14,
                   15, 16])
  
# view array
print("Given Array:\n", arr)
  
# declare k
k = 2
  
# find the mean 
output = numpy.mean(arr.reshape(-1, k),
                    axis=1)
  
# view output
print("Output Array:\n", output)

Output:

Given Array:
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
Output Array:
[ 1.5  3.5  5.5  7.5  9.5 11.5 13.5 15.5]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :