Statistics in Python using the statistics module | Python statistics package

TogglenavigationPythonforUndergraduateEngineersAboutBookGearNowArchivesstatisticsStatisticsinPythonusingthestatisticsmoduleInthispost,we'lllookatacoupleofstatisticsfunctionsinPython.ThesestatisticsfunctionsarepartofthePythonStandardLibraryinthestatisticsmodule.Thefourfunctionswe'lluseinthispostarecommoninstatistics:mean-averagevaluemedian-middlevaluemode-mostoftenvaluestandarddeviation-spreadofvaluesToaccessPython'sstatisticsfunctions,weneedtoimportthefunctionsfromthestatisticsmoduleusingthestatement:fromstatisticsimportmean,median,mode,stdevAftertheimportstatement,thefunctionsmean(),median(),mode()andstdev()(standarddeviation)canbeused.SincethestatisticsmoduleispartofthePythonStandardLibrary,noexternalpackagesneedtobeinstalled.Let'simaginewehaveadatasetof5testscores.Thetestscoresare60,83,91and100.ThesetestscorescanbestoredinaPythonlist.Pythonlistsaredefinedwithsquarebrackets[].ElementsinPythonlistsareseparatedwithcommas.In [1]:fromstatisticsimportmean,median,mode,stdevtest_scores=[60,83,83,91,100]Calculatethemean¶Tocalculatethemean,oraverageofourtestscores,usethestatisticsmodule'smean()function.In [2]:mean(test_scores)Out[2]:83.4Calculatethemedian¶Tocalculatethemedian,ormiddlevalueofourtestscores,usethestatisticsmodule'smedian()function.Ifthereareanoddnumberofvalues,median()returnsthemiddlevalue.Ifthereareanevennumberofvaluesmedian()returnsanaverageofthetwomiddlevalues.In [3]:median(test_scores)83Out[3]:83Calculatethemode¶Tocalculatethemode,ormostoftenvalueofourtestscores,usethestatisticsmodule'smode()function.Ifthereismorethanonenumberwhichoccursmostoften,mode()returnsanerror.>>>mode([1,1,2,2,3])StatisticsError:nouniquemode;found2equallycommonvaluesIfthereisnovaluethatoccursmostoften(allthevaluesareuniqueoroccurthesamenumberoftimes),mode()alsoreturnsanerror.>>>mode([1,2,3])StatisticsError:nouniquemode;found3equallycommonvaluesIn [4]:mode(test_scores)Out[4]:83Calculatethestandarddeviation¶Tocalculatethestandarddeviation,orspreadofthetestscores,usethestatisticsmodul


常見投資理財問答


延伸文章資訊