如何计算列表中每三个值的平均值

Sac*_*hin 1 python numpy list mean chunks

我有一个清单:

first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
Run Code Online (Sandbox Code Playgroud)

我想要另一个具有三个值的平均值的列表,因此新列表是:

new = [2,5,8,11,14,17]
Run Code Online (Sandbox Code Playgroud)

新列表中将只有 6 个值,因为第一个列表中只有 18 个元素。

我正在寻找一种优雅的方法来执行此操作,并且对大列表使用最少的步骤。

ssh*_*124 8

使用numpy,您可以将 18 个元素的列表重塑为一个形状数组,(6, 3)然后对行取平均值

import numpy as np
a = np.array(first)

>>> a.reshape(-1, 3)
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12],
       [13, 14, 15],
       [16, 17, 18],

>>> a.reshape(-1, 3).mean(axis=1)
array([ 2.,  5.,  8., 11., 14., 17.])
Run Code Online (Sandbox Code Playgroud)

使用-1innp.reshape(-1, 3)实际上允许您将此方法用于大小为 3 的倍数的任何数组,它会自动适当地调整第一个维度的大小


Guy*_*Guy 5

您可以first使用以 3 个间隔迭代的 for 循环

import statistics

new = [statistics.mean(first[i:i + 3]) for i in range(0, len(first), 3)]
print(new) # [2, 5, 8, 11, 14, 17]
Run Code Online (Sandbox Code Playgroud)


Erf*_*fan 5

这是使用pandaswith的解决方案groupby

import pandas as pd

ser = pd.Series(first)
ser.groupby(ser.index//3).mean()

0     2
1     5
2     8
3    11
4    14
5    17
dtype: int64
Run Code Online (Sandbox Code Playgroud)