搜索
首页后端开发Python教程Python中的数学模块:统计

Mathematical Modules in Python: Statistics

Python的statistics模块提供强大的数据统计分析功能,帮助我们快速理解数据整体特征,例如生物统计学和商业分析等领域。无需逐个查看数据点,只需查看均值或方差等统计量,即可发现原始数据中可能被忽略的趋势和特征,并更轻松、有效地比较大型数据集。

本教程将介绍如何计算平均值和衡量数据集的离散程度。除非另有说明,本模块中的所有函数都支持使用mean()函数计算平均值,而非简单的求和平均。 也可使用浮点数。

import random
import statistics
from fractions import Fraction as F

int_values = [random.randrange(100) for x in range(9)]
frac_values = [F(1, 2), F(1, 3), F(1, 4), F(1, 5), F(1, 6), F(1, 7), F(1, 8), F(1, 9)]

mix_values = [*int_values, *frac_values]

print(statistics.mean(mix_values))
# 929449/42840

print(statistics.fmean(mix_values))
# 21.69582166199813

从Python 3.8版本开始,可以使用geometric_mean(data, weights=None)harmonic_mean(data, weights=None)函数计算几何平均数和调和平均数。

几何平均数是将数据中所有n个值的乘积开n次方根的结果。由于浮点数误差,某些情况下结果可能略有偏差。几何平均数的一个应用是快速计算复合年增长率。例如,一家公司四年的销售额分别为100、120、150和200。三年的增长率分别为20%、25%和33.33%。公司的平均销售增长率将更准确地用百分比的几何平均数表示。算术平均数总是会给出错误且略高的增长率。

import statistics

growth_rates = [20, 25, 33.33]

print(statistics.mean(growth_rates))
# 26.11

print(statistics.geometric_mean(growth_rates))
# 25.542796263143476

调和平均数只是数据的倒数的算术平均数的倒数。如果数据中包含零或负数,则会引发StatisticsError异常。

调和平均数用于计算比率和速率的平均值,例如计算平均速度、密度或并联电阻。以下代码计算某人以特定速度行驶固定路程(此处为100公里)时的平均速度。

import statistics

speeds = [30, 40, 60]
distance = 100

total_distance = len(speeds) * distance
total_time = 0

for speed in speeds:
    total_time += distance / speed

average_speed = total_distance / total_time

print(average_speed)
# 39.99999999999999

print(statistics.harmonic_mean(speeds))
# 40.0

需要注意的是,Python 3.8中的multimode()函数在有多个出现频率相同的数值时,可以返回多个结果。

import statistics

favorite_pet = ['cat', 'dog', 'dog', 'mouse', 'cat', 'cat', 'turtle', 'dog']

print(statistics.multimode(favorite_pet))
# ['cat', 'dog']

计算中位数

依赖众数计算中心值可能会产生误导。如前所述,众数始终是出现频率最高的数据点,而不管数据集中的其他值如何。另一种确定中心位置的方法是使用pvariance(data, mu=None)函数计算给定数据集的总体方差。

此函数的第二个参数是可选的。如果提供mu的值,则应等于给定数据的均值。如果缺少该值,则会自动计算均值。此函数在您想要计算整个总体的方差时很有用。如果您的数据只是总体的样本,则可以使用variance(data, xBar=None)函数计算样本方差,其中xBar是给定样本的均值,如果没有提供,则会自动计算。

可以使用pstdev(data, mu=None)stdev(data, xBar=None)函数分别计算总体标准差和样本标准差。

import random
import statistics
from fractions import Fraction as F

int_values = [random.randrange(100) for x in range(9)]
frac_values = [F(1, 2), F(1, 3), F(1, 4), F(1, 5), F(1, 6), F(1, 7), F(1, 8), F(1, 9)]

mix_values = [*int_values, *frac_values]

print(statistics.mean(mix_values))
# 929449/42840

print(statistics.fmean(mix_values))
# 21.69582166199813

从上面的例子可以看出,较小的方差意味着更多的数据点与均值的值更接近。您还可以计算小数和分数的标准差。

总结

在本系列的最后一个教程中,我们学习了statistics模块中提供的不同函数。您可能已经注意到,提供给函数的数据在大多数情况下都是排序的,但它不必排序。在本教程中,我使用了排序列表,因为它们使更容易理解不同函数返回的值与输入数据之间的关系。

以上是Python中的数学模块:统计的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

与同一元素的Python串联列表与同一元素的Python串联列表May 11, 2025 am 12:08 AM

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

解释与编译语言:Python的位置解释与编译语言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循环时:您什么时候在Python中使用?循环时:您什么时候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具