Average of Each N-length Consecutive Segment in a List - Python
Last Updated :
18 Jan, 2025
The task is to compute the average of each n-length consecutive segment from a given list. For example, if the input list is [1, 2, 3, 4, 5, 6]
and n = 2
, the output should be [1.5, 2.5, 3.5, 4.5, 5.5]
. Let's discuss various ways in this can be achieved.
Using List Comprehension
This method uses list slicing within a list comprehension to calculate averages of consecutive segments.
Python
# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2
# Calculate averages using list comprehension
res = [sum(a[i:i+n]) / n for i in range(len(a) - n + 1)]
print(res)
Output[1.5, 2.5, 3.5, 4.5, 5.5]
Explanation:
- For each index in the range of valid segments, we slice
a
from i
to i + n
. - The sum of the sliced segment is divided by
n
to compute the average. - This method is simple and efficient for small to medium-sized lists.
Let's explore some more methods and see how we can find average of each n length consecutive segments in a list.
This approach uses the islice() function from itertools to create a sliding window and calculate averages.
Python
from itertools import islice
# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2
# Create a sliding window and calculate averages
res = [(sum(islice(a, i, i+n))) / n for i in range(len(a) - n + 1)]
print(res)
Output[1.5, 2.5, 3.5, 4.5, 5.5]
Explanation:
islice(a, i, i + n)
creates isslicea sliding window of size n from index i.- The sum of each window is divided by n to compute the average.
- This method is slightly more efficient for larger lists because it avoids unnecessary slicing.
Using NumPy Convolution
This method employs NumPy’s convolution operation to calculate the averages.
Python
import numpy as np
# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2
# Calculate averages using convolution
res = np.convolve(a, np.ones(n) / n, mode='valid')
print(res)
Output[1.5 2.5 3.5 4.5 5.5]
Explanation:
np.ones(n) / n
creates a filter of size n
where each element is 1/n
.- The convolution operation slides this filter over the list
a
, computing the average for each segment. - NumPy operations are highly optimized for numerical computations and are efficient for large datasets.
Using for Loop
In this approach, we iterate through the list using a manual for loop to calculate segment averages.
Python
# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2
# Initialize the result list
res = []
# Calculate averages manually
for i in range(len(a) - n + 1):
segment = a[i:i+n]
avg = sum(segment) / n
res.append(avg)
print(res)
Output[1.5, 2.5, 3.5, 4.5, 5.5]
Explanation:
- loop iterates through the indices of valid segments.
- For each index, a slice is taken, and its average is computed and appended to the result list.
Using Pandas Rolling
This method uses the rolling function from pandas, which is ideal for handling rolling window operations.
Python
import pandas as pd
# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2
# Create a pandas Series and calculate rolling averages
res = pd.Series(a).rolling(window=n).mean().dropna().tolist()
print(res)
Output[1.5, 2.5, 3.5, 4.5, 5.5]
Explanation:
- The pandas rolling function computes the rolling average for a given window size.
- .dropna() NaN values at the beginning, resulting from the initial incomplete window.
- This method is highly efficient for large datasets but introduces an external library dependency.
Similar Reads
Break a List into Chunks of Size N in Python The goal here is to break a list into chunks of a specific size, such as splitting a list into sublists where each sublist contains n elements. For example, given a list [1, 2, 3, 4, 5, 6, 7, 8] and a chunk size of 3, we want to break it into the sublists [[1, 2, 3], [4, 5, 6], [7, 8]]. Letâs explor
3 min read
Find average of a list in python We are given a list of numbers and the task is to find the average (or mean) value of its elements. For example, if we have a list nums = [10, 20, 30, 40], the sum of the elements is 10 + 20 + 30 + 40, which equals 100. The number of elements in the list is 4. So, the average is calculated as 100 /
2 min read
Python | Consecutive remaining elements in list Sometimes, while working with Python list, we can have a problem in which we need to get the consecutive elements count remaining( including current ), to make certain decisions beforehand. This can be a potential subproblem of many competitive programming competitions. Let's discuss a shorthand whi
2 min read
How to Calculate Moving Averages in Python? In this discussion we are going to see how to Calculate Moving Averages in Python in this discussion we will write a proper explanation What is Moving Averages?Moving Averages, a statistical method in data analysis, smooths fluctuations in time-series data to reveal underlying trends. Calculating th
11 min read
Python | Consecutive elements grouping in list Sometimes, while working with Python lists, we can have a problem in which we might need to group the list elements on basis of their respective consecutiveness. This kind of problem can occur while data handling. Let's discuss certain way in which this task can be performed. Method 1: Using enumera
5 min read