×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Averaging over every n elements of a NumPy array

Learn, how to average over every n elements of a NumPy array in Python? By Pranit Sharma Last updated : October 10, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a NumPy array and we need to create a new array which is the average over every consecutive triplet of elements so that the new array will be one-third of the size as the original.

NumPy Array - Averaging over every n elements

If the length of the array is divisible by 3, using the numpy.mean() method would be a better option where we will reshape the array by taking 3 columns of a row at a time.

Let us understand with the help of an example,

Python program for averaging over every n elements of a NumPy array

# Import numpy
import numpy as np

# Creating numpy array
arr = np.array([52,53,99,100,10,30])

# Display original array
print("Orignal array:\n",arr,"\n")

# Calculating mean
res = np.mean(arr.reshape(-1, 3), axis=1)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Averaging over every n elements of a NumPy array

Python NumPy Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.