• 主要介绍了python计算一个序列的平均值方法,涉及Python递归遍历与数学计算的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
  • 主要介绍了Python简单计算数组元素平均值方法,涉及Python简单数组遍历与数学运算相关操作技巧,需要的朋友可以参考下
  • python列表平均值函数Mathematics and programming go hand in hand. If you are a programmer, at some point you will have to use mathematics. 数学和程序设计齐头并进。 如果您是程序员,则有时必须使用数学。 ...


    Mathematics and programming go hand in hand. If you are a programmer, at some point you will have to use mathematics.

    数学和程序设计齐头并进。 如果您是程序员,则有时必须使用数学。

    Data science, machine learning, artificial intelligence, and cryptocurrencies are all based on complex underlying mathematical principles.


    However, using math functions doesn't have to be complex! Python abstracts everything away, so once you understand the concepts, you will not need to understand the full details of the implementation.

    但是,使用数学函数不必太复杂! Python将所有内容抽象化,因此,一旦您理解了这些概念,就无需了解实现的全部细节。

    数学不必太吓人 (Math doesn't have to be scary)

    There are a lot of mathematical functions you will come across. If you are working with data or analytics, it's important that you understand some mathematical principles and functions.

    您将遇到很多数学函数。 如果您正在使用数据或分析,那么了解一些数学原理和函数很重要。

    One such function you must understand is the mean function.


    Don't be put off by the name – there is nothing mean (pun intended) about the mean function in Python.

    不要被名字拖延– Python中的mean函数没有任何意义(双关语)。

    This post is self contained, but I expect you have some experience working with Python and that you know what a Python list is. If not, check out this article before moving on.

    这篇文章是独立的,但是我希望您有使用Python的经验,并且知道Python列表是什么。 如果不是这样,请先阅读本文,然后再继续。

    Once you're finished, come back and join me for a deep dive into the mean function.


    统计 (Statistics )

    So you want to learn about the mean function. That's great! But before we look at this function its important to look at the discipline from which it originates: statistics.

    因此,您想了解mean函数。 那很棒! 但是,在我们研究此功能之前,先了解其起源的学科很重要:统计学。

    In the image above we see a graph. A graph is a pictorial representation that shows the relationship of one variable in relation to another.

    在上图中,我们看到了一个图形。 图形是一种图形表示形式,显示了一个变量与另一个变量之间的关系。

    Graphs are useful because they allows us to organize data so that we can quickly see trends and relationships between the data. A graph is just one tool that we can use to visualize and analyze data.

    图形之所以有用,是因为它们使我们能够组织数据,以便我们可以快速查看数据之间的趋势和关系。 图形只是我们可以用来可视化和分析数据的一种工具。

    Statistics is a branch of mathematics that allows us to have a systematic way of classifying, analyzing and interpreting data. This is important because with statistics, we have a collection of ready made tools to do each of those things.

    统计学是数学的一个分支,它使我们能够有系统地分类,分析和解释数据。 这一点很重要,因为有了统计信息,我们就可以使用现成的工具来完成所有这些事情。

    Imagine if you needed to reinvent a saw every time you needed to cut a piece of wood. We would many people calling saws by different names, even though they do the same thing. To avoid this problem, we gave the saw a name that everyone can refer to it by.

    想象一下,如果您每次需要切割一块木头时都需要重新制作锯。 即使他们做同样的事情,我们也会有许多人用不同的名字称锯。 为避免出现此问题,我们给了锯一个名称,每个人都可以引用它。

    The same happens in statistics — we have tools well known tools that everyone is familiar with. One such tool is the mean.

    统计数据中也是如此-我们拥有大家都熟悉的众所周知的工具。 平均值就是这样一种工具。

    模式,中位数和均值 (Mode, Median and Mean)

    Though mean is perfectly capable of standing on its own, it's usually taught as part of a trio, which includes the mode, median, and mean.


    Let's look at a group of numbers so you'll understand what is happening here. Imagine you have the numbers below:

    让我们看一组数字,以便您了解这里发生的情况。 假设您有以下数字:

    1,2,3,3,4,6,9 (1, 2, 3, 3, 4, 6, 9)

    Say we wanted to express which number occurs the most times. It would be 3, and the name we give this property is mode. The mode is the number which is the most frequent in a set we are examining.

    假设我们想表达哪个数字出现次数最多。 它将是3,而我们给此属性的名称是mode。 模式是我们正在检查的集合中最频繁的数字。

    The number in the middle of an ordered set is called the median. To find the median of a numerical set, arrange the numbers from smallest to largest and then look at the number in the middle. The set of numbers above is already arranged from least to greatest, so the median number is also 3.

    有序集合中间的数字称为中位数。 要查找数值集的中位数,请从最小到最大排列数字,然后查看中间的数字。 上面的数字集已经按照从最小到最大的顺序排列,因此中位数也是3。

    Finally, the mean is another way to refer to the average of the set. To find the mean, just add all the numbers together and divide it by the total number of elements in the set. In the case of the numbers above, if we add them all together, we get 28. The total number of items in the set is  7, so our mean is 4.

    最后,均值是引用集合平均值的另一种方法。 要找到均值,只需将所有数字加在一起,然后除以集合中元素的总数即可。 在上述数字的情况下,如果将它们全部加在一起,我们将得到28。集合中的项目总数为7,因此我们的均值为4。

    为什么我们需要中庸? (Why Do We Need the Mean?)

    So at this point you may be wondering why would we need to find the mean of a number anyway.


    The thing is, even statistics itself is subdivided into several groups. Just as you have tools that are used for working with wood and others for working with metal, some tools in statistics are grouped into classes since they are used for a similar purpose.

    事实是,甚至统计本身也被细分为几组。 就像您拥有用于木材加工的工具和其他用于金属加工的工具一样,统计中的某些工具也归类为类,因为它们用于类似目的。

    One such group in statistics is called summary statistics. One of the things statistics is used for is to describe data, and summary statistics is a collection of tools used for that purpose. One of the items in that class of tools is the mean.

    统计中的一种这样的组称为汇总统计。 统计信息的用途之一是描述数据,摘要统计信息是用于此目的的工具的集合。 该类工具中的一项是平均值。

    The mean is important due to helping us analyze what is known as a distribution. In statistics, a distribution is a method we use to look at a variable we want information on. Using a distribution we will look at the values of this variable and how often it occurs.

    由于有助于我们分析所谓的分布,因此平均值很重要。 在统计数据中,分布是一种用于查看需要信息的变量的方法。 使用分布,我们将查看此变量的值及其发生的频率。

    If we collect data, a common type of distribution we see is the normal distribution which takes the form of the bell curve:


    That is to say the variable will have a common value toward which it tends, as well as a starting point and an end point.


    What the mean does is that it allows us to take a distribution like this and look at the central tendency of the variable, which is the point at which the values of the variable tend to cluster.


    Thus we can say the mean describes the central tendency of the distribution.


    用Python计算平均值 (Calculating the Mean in Python )

    We can manually calculate the mean if we have a small numerical data set it we have a few values to work with. However, when we have hundreds or thousands of values in a data set it becomes impossible to calculate it by hand.

    如果我们有一个小的数值数据集,我们可以手动计算平均值,但我们需要处理一些值。 但是,当我们在一个数据集中有成百上千个值时,就无法手动计算它。

    Since Python is a "batteries included" language, the way we can do this is to use the mean function of the statistics module within Python.


    Let's use the mean function to calculate the mean of the numerical data set we had earlier in the post:


    # 1. import the statistics module
    import statistics
    # 2. list containing our numerical data set
    numerical_data_set = [1, 2, 3, 3, 4, 6, 9]
    # 3. calculate the mean
    calc_mean = statistics.mean(numerical_data_set)
    # 4. print our calculated mean
    print("Mean is: ", calc_mean)

    Our code consists of a 4 step sequence that we can use to calculate the mean:


    1. We import the statistics module that contains our mean function

    2. We create a Python list containing the numerical data set of which we would like to calculate the mean

    3. We calculate the mean and store the result in a variable, calc_mean


    4. We output our calculated mean so that we can get visual feedback


    When we run the code, we will get the following output:


    The program outputs the same value as our manual calculations. When we are working with large data sets, this function will be able to scale to handle whatever we can throw at it.

    该程序输出与我们的手动计算相同的值。 当我们处理大型数据集时,此函数将能够扩展以处理我们可以扔给它的任何东西。

    结语 (Wrapping Up)

    In this post we looked at the mean function in Python. We began by discussing statistics as a whole, then took a deep dive into mean.

    在这篇文章中,我们研究了Python中的mean函数。 我们从讨论整个统计数据开始,然后深入探讨均值。

    Now that you have a solid understanding of statistics and the mean function in Python, you can use it in your own programs.


    If you liked this article, then you may also be curious about learning about data structures and algorithms. If you want a simple, clear, step by step guide to learning about data structures and algorithms without having to write a single line of code, then you can check out the book Codeless Data Structures and Algorithms.

    如果您喜欢本文,那么您也可能对学习数据结构和算法感到好奇。 如果您想要一个简单,清晰,分步的指南来学习数据结构和算法,而不必编写任何代码,那么可以参考《无代码数据结构和算法》一书。

    Read the book here:


    翻译自: https://www.freecodecamp.org/news/how-to-calculate-the-average-of-a-list-statistics-and-pythons-mean-function-explained-in-detail/


  • python平均值

    万次阅读 多人点赞 2019-12-27 20:49:59
    python平均值 首先我们先来了解一下计算平均数的IPO模式. 输入:待输入计算平均数的数。 处理:平均数算法 输出:平均数 推荐:《python教程》 明白了程序的IPO模式之后,我们打开本地的python的IDE工具,并新建一...







    编码完成后,记得保存,然后进行调试运行。按F5键或者点击菜单栏中的“run”-》“run model”来运行程序。

  • python实现计算移动平均值MA

    万次阅读 2020-12-19 11:20:03
    目录 1、题目描述 2、代码实现 3、运行结果 1、题目描述 ...计算移动平均值MA...m),用python计算1到m的这m个整数的n周期移动平均值(共有m-n+1个值)。 输入样例: 输入正整数m: 3 输入正整数n: 2 输出...






    计算移动平均值MA(Moving Average)。如有一列数1、2、3、4、5、6、7和8,按周期为3计算,则可计算出6个值,依次为(1+2+3)/3、(2+3+4)/3、(3+4+5)/3、(4+5+6)/3、(5+6+7)/3和(6+7+8)/3。由用户输入m和n( 输入样例:
    输入正整数m:    3
    输入正整数n:     2

    移动平均值序列是:[1.5, 2.5]


    #!/usr/bin/env python 
    # -*- coding:utf-8 -*-
    from xlwt.compat import xrange
    def fun():
        m = int(input("输入正整数m:\t"))
        n = int(input("输入正整数n:\t"))
        result = []
        for i in range(1, m + 1):
            if (i <= m - n + 1):
                avg = sum(list(xrange(i, i + n))) / n
        print("移动平均值序列是:", result)
    if __name__ == '__main__':


    输入正整数m:	3
    输入正整数n:	2
    移动平均值序列是: [1.5, 2.5]

  • 编写函数,计算列表的最大、最小和平均值。编写主程序,输入列表,调用函数计算最大、最小和平均值,在主程序中显示它们。注,不能使用Python及第三方库的函数直接求。 代码: ''' 编写函数,计算列表的最大、最小...




    written by tyb
    def inputList():
        #num_list = list(map(int, input().split()))  # 或者
        num_list = [int(i) for i in input().split()] # 接收一段以空格隔开的整数的输入
        return num_list
    def outputList(list):
        for i in range(len(list)):
    def findMax(list):
        num_max = list[0] #记录最大值
        for i in range(len(list)):
            if list[i] >= num_max:
                num_max = list[i]
        return num_max
    def findMin(list):
        num_min = list[0] #记录最小值
        for i in range(len(list)):
            if list[i] <= num_min:
                num_min = list[i]
        return num_min
    def averageValue(list):
        value = 0 #记录平均值
        sum = 0 #求和
        for i in range(len(list)):
            sum = sum + list[i]
        value = sum/len(list)
        return value
    if __name__ == '__main__':
        list = inputList()
        max = findMax(list)
        min = findMin(list)
        value = averageValue(list)
  • Python计算平均

    千次阅读 2020-06-09 11:11:47
    计算平均分 编写一个程序,根据输入的 3 个成绩,计算平均分。 a=float(input("第一门成绩:")) b=float(input("第二门成绩:")) c=float(input("第三门成绩:")) num=(a+b+c)/3 print("平均分为:"+str(num)) ...
  • 今天小编就为大家分享一篇python 计算平均平方误差的实例 (MSE),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • python列表查找值Hi Folks! In this article, we will have a look at the various ways to find the average... 在本文中,我们将介绍在Python List中查找列表平均值的各种方法 。 In general, an average is a va...
  • Python-计算平均值,方差,中位数

    千次阅读 2019-04-19 19:07:16
    #计算平均值 def mean(numbers): s=0.0 for num in numbers: s += num return s / len(numbers) #计算方差 def dev(numbers,mean): sdev = 0.0 for num in numbers: sdev += (num - mean)**2 return pow...
  • 首先是数据源:#需要求加权平均值的数据列表 elements = [] #对应的权值列表 weights = []使用numpy直接求:import numpy as np np.average(elements, weights=weights)附纯python写法:# 不使用numpy写法1 round...
  • 通常,我们需要将多个栅格求平均,例如,将一年中每个月的NDVI加起来除以12,就会等到月均NDVI,该过程虽然在栅格计算器中可以实现,但是当时间序列较长时就比较费事,此时,python代码是不二的选择。 下图所示为...
  • python计算各类移动平均线,python计算各类移动平均线,
  • python计算平均值、方差、中位数,注释齐全,基本为列表的学习和应用。 def getNum(): nums = [] iNumStr = input("请输入数字(回车退出):") while iNumStr != "": # 判断用户输入的数字是否为空,若为空则...
  • python平均值小程序

    千次阅读 2016-10-29 18:08:19
    def start(): print('请输入求平均值的数字,数字之间用逗号隔开\n') num = input() num1 = num.split(',') try: while True: num1.remove(',') except: pass try: r=list
  • 今天小编就为大家分享一篇Python 实现输入任意多个数,并计算平均值的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • Python+GDAL | 计算栅格平均值

    千次阅读 2019-05-29 11:33:33
    这篇文章主要描述了如何使用GDAL设置掩膜,并计算平均值。 代码 from osgeo import gdal import os, sys import numpy os.chdir(r'D:\Python学习资料\GDAL\data\ospy_data4') #注册类 gdal.AllRegister() #打开栅格...
  • 今天小编就为大家分享一篇python求加权平均值的实例(附纯python写法),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • Python :平均值(代码)

    万次阅读 2019-06-25 16:03:07
    def average(nums): sum = 0 for x in nums: sum += x avg = sum / len(nums) print(avg) return avg def main(): average([2, 4, 6, 8, 20, 50, 70]) if name == ‘main’: main()
  • df = pandas.read_excel('test.xlsx') df = pandas.pivot_table(df, index=['a'], columns=['b'], aggfunc=numpy.sum) ...想计算周日均数据变成这样 pv uv 20180105~20180111 1 1 20180111~20180118 2 2
  • from math import sqrt def getNum ( ) : nums = [ ] iNumStr = input ( "输入数字(回车退出):" ..."平均值:{},方差:{:.2},中位数:{}." . format ( m , dev ( n , m ) , median ( n ) ) )
  • Python学习笔记:计算数组平均值

    千次阅读 2020-08-04 09:59:04
    list=[10000,8500, 9000,7000,8000,8000,9000,20000,15000,16000,5000] AVGIncome=sum(list)/len(list) print(AVGIncome)
  • python爬虫练习1:计算评分平均值

    千次阅读 2019-08-25 19:12:39
    抽取某本书的前50条短评内容并计算评分的平均值。提示:有的评论中并不包含评分。 代码: # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import requests from bs4 import ...
  • python 计算简单移动平均

    千次阅读 2019-10-03 20:33:59
    简单移动平均使用,window 参数表示使用前20个数据求平均。 df_stockload['Ma20'] = df_stockload.Close.rolling(window=20).mean()#增加M20移动平均线 ...DataFrame.dropna()方法删除NaN。其中...



1 2 3 4 5 ... 20
收藏数 91,150
精华内容 36,460


python 订阅