[英]calculate rolling average of each list in 2d list in Python
I have a 2d python list that I want to plot the moving average of.我有一个 2d python 列表,我想要 plot 的移动平均线。 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.我不确定如何在 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]]
我的输入是这个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我想要的 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]]
If don't want to use libraries like pandas or numpy you can calculate yourself in a list comprehension:如果不想使用 pandas 或 numpy 之类的库,您可以在列表理解中计算自己:
[[0.5*(a[i] + a[i+1]) for i in range(len(a)-1)] for a in value_list]
In your case it seems you need a slicing window of size 2, so:在你的情况下,你似乎需要一个大小为 2 的切片 window,所以:
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:如果您需要其他 window 尺寸,您可以定义一个变量w
和:
[np.convolve(l, np.ones(w)/w, mode="valid") for l in value_list]
Here the more simpler and clear approach for beginner in python.这里是 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:所需的 output 是:
[[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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.