在 Python 中查找 Numpy 数组列表的平均值


Numpy 是一个非常强大的 Python 库,用于数字数据处理。它通常以数组形式获取数据,并应用各种函数(包括统计函数)以从数组中获取结果。在本文中,我们将学习如何获得给定数组的平均值。

有平均值

平均值函数可以接受一个数组,并给出其中所有元素的数学平均值。因此,我们设计一个 for 循环来跟踪输入的长度并遍历每个数组来计算其平均值。

示例

 在线演示

import numpy as np

# GIven Array
Arrays_In = [np.array([11, 5, 41]),
         np.array([12, 13, 26]),
         np.array([56, 20, 51])]

# Resultihg Array
Arrays_res = []

# With np.mean()
for x in range(len(Arrays_In)):
   Arrays_res.append(np.mean(Arrays_In[x]))

# Result
print("The means of the arrays: \n",Arrays_res)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

运行上述代码,将得到以下结果 -

The means of the arrays:
[19.0, 17.0, 42.333333333333336]

有平均数

它与上述方法非常相似,但使用平均数函数而不用平均值函数。它给出了完全相同的结果。

示例

 在线演示

import numpy as np

# GIven Array
Arrays_In = [np.array([11, 5, 41]),
         np.array([12, 13, 26]),
         np.array([56, 20, 51])]

# Resultihg Array
Arrays_res = []

# With np.average()
for x in range(len(Arrays_In)):
   Arrays_res.append(np.average(Arrays_In[x]))

# Result
print("The means of the arrays: \n",Arrays_res)

输出

运行上述代码,将得到以下结果 -

The means of the arrays:
[19.0, 17.0, 42.333333333333336]

更新于: 2020-08-26

710 次浏览

开启你的 职业生涯

完成课程,获得认证

开始
广告