Home > Back-end >  calculate rolling average of each list in 2d list in Python
calculate rolling average of each list in 2d list in Python

Time:04-13

I have a 2d python list that I want to plot the moving average of. So for each list within the list I want to calculate the moving average seperately. I am not sure how to apply rolling on a list like a Pandas df.

I first converted my 2d list to numeric

value_list = [pd.to_numeric(lst, errors='ignore') for lst in value_list]

My input is this value_list = [[1,2,3,4,6,2,1,5,2,13,14],[4,5,6,12,32,42,75],[7,8,9,83,12,16]]

My desired output

value_list = [[1.5,2.5,3.5,5,4,1.5,3,3.5,7.5,13.5],[4.5,5.5,9,22,37,58.5],[7.5,8.5,46,47.5,14]]

CodePudding user response:

If don't want to use libraries like pandas or numpy you can calculate yourself in a list comprehension:

[[0.5*(a[i]   a[i 1]) for i in range(len(a)-1)] for a in value_list]

CodePudding user response:

In your case it seems you need a slicing window of size 2, so:

import numpy as np
[np.convolve(l, np.ones(2)/2, mode="valid") for l in value_list]

if you need other window sizes you can define a variable w and:

[np.convolve(l, np.ones(w)/w, mode="valid") for l in value_list]

CodePudding user response:

Here the more simpler and clear approach for beginner in python.

import pandas as pd


def moving_average(numbers, window_size):

    numbers_series = pd.Series(numbers)
    windows = numbers_series.rolling(window_size)
    moving_averages = windows.mean()

    return moving_averages.tolist()[window_size - 1:]


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    value_list = [[1, 2, 3, 4, 6, 2, 1, 5, 2, 13, 14], [4, 5, 6, 12, 32, 42, 75], [7, 8, 9, 83, 12, 16]]
    output_list = []
    for nums in value_list:
        output_list.append(moving_average(nums, 2))

    print(output_list)

Required output is:

[[1.5, 2.5, 3.5, 5.0, 4.0, 1.5, 3.0, 3.5, 7.5, 13.5], [4.5, 5.5, 9.0, 22.0, 37.0, 58.5], [7.5, 8.5, 46.0, 47.5, 14.0]]
  • Related