Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何计算列表中每三个值的平均值_Python_List_Numpy_Mean_Chunks - Fatal编程技术网

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

Python 如何计算列表中每三个值的平均值,python,list,numpy,mean,chunks,Python,List,Numpy,Mean,Chunks,我有一份清单: first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] 我想要另一个平均值为三个值的列表,因此新列表为: new = [2,5,8,11,14,17] 新列表中只有6个值,因为第一个列表中只有18个元素 我正在寻找一种优雅的方法来实现这一点,只需对一个大列表执行最少的步骤。使用numpy,您可以将18个元素的列表重塑为一个形状数组(6,3),然后对行进行平均 import numpy as np a = np.array(

我有一份清单:

first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
我想要另一个平均值为三个值的列表,因此新列表为:

new = [2,5,8,11,14,17]
新列表中只有6个值,因为第一个列表中只有18个元素


我正在寻找一种优雅的方法来实现这一点,只需对一个大列表执行最少的步骤。

使用
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.])


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

使用
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.])


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

您可以使用以3个间隔迭代的for循环获取
first
的一部分

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]

您可以首先使用以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]

下面是另一个解决方案,使用它可以获得列表中每三个数字的每个块的平均值

>>> from statistics import mean
>>> first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
>>> [mean(x) for x in zip(*[iter(first)] * 3)]
[2, 5, 8, 11, 14, 17]

下面是另一个解决方案,使用它可以获得列表中每三个数字的每个块的平均值

>>> from statistics import mean
>>> first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
>>> [mean(x) for x in zip(*[iter(first)] * 3)]
[2, 5, 8, 11, 14, 17]

以下是使用
pandas
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

以下是使用
pandas
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

first
中的元素数是否总是可以被窗口大小整除?这是否回答了您的问题?对于NumPy:first
中的元素数是否总是可以被窗口大小整除?这是否回答了您的问题?对于NumPy: