Home Backend Development Python Tutorial Mathematical Modules in Python: Statistics

Mathematical Modules in Python: Statistics

Mar 09, 2025 am 11:40 AM

Mathematical Modules in Python: Statistics

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively.

This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the average value using the mean() function rather than simply summing the average. Floating point numbers can also be used.

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
Copy after login
Copy after login

Starting with Python 3.8, you can use the geometric_mean(data, weights=None) and harmonic_mean(data, weights=None) functions to calculate the geometric mean and the harmonic mean.

The geometric mean is the result of dividing the product of all n values ​​in the data to the root of the n power. Due to floating point errors, the results may be slightly biased in some cases. One application of geometric mean is to quickly calculate the compound annual growth rate. For example, a company's four-year sales are 100, 120, 150, and 200, respectively. The growth rates in three years were 20%, 25% and 33.33% respectively. The average sales growth rate of a company will be more accurately expressed as a geometric average of percentages. The arithmetic mean always gives an incorrect and slightly higher rate of growth.

import statistics

growth_rates = [20, 25, 33.33]

print(statistics.mean(growth_rates))
# 26.11

print(statistics.geometric_mean(growth_rates))
# 25.542796263143476
Copy after login

The harmonic mean is just the reciprocal of the arithmetic mean of the reciprocal of the data. If the data contains zero or negative numbers, a StatisticsError exception is thrown.

The harmonic average is used to calculate the average of ratios and rates, such as calculating the average speed, density, or parallel resistance. The following code calculates the average speed when someone travels a fixed distance (here is 100 km).

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
Copy after login

It should be noted that when there are multiple values ​​with the same frequency of occurrence, the multimode() function in Python 3.8 can return multiple results.

import statistics

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

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

Calculate the median

Calculating the center value with a mode may be misleading. As mentioned earlier, mode is always the most frequent data point, regardless of other values ​​in the dataset. Another way to determine the center position is to use the pvariance(data, mu=None) function to calculate the population variance of a given dataset.

The second parameter of this function is optional. If a value of mu is provided, it should be equal to the mean of the given data. If this value is missing, the mean is calculated automatically. This function is useful when you want to calculate the variance of the entire population. If your data is just a sample of the population, you can use the variance(data, xBar=None) function to calculate the sample variance, where xBar is the mean of a given sample, which is automatically calculated if not provided.

The population standard deviation and sample standard deviation can be calculated using the pstdev(data, mu=None) and stdev(data, xBar=None) functions respectively.

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
Copy after login
Copy after login

As can be seen from the above example, a smaller variance means that more data points are closer to the value of the mean. You can also calculate the standard deviation of decimals and fractions.

Summary

In the last tutorial in this series, we learned the different functions provided in the statistics module. You may have noticed that the data provided to the function is sorted in most cases, but it does not have to be sorted. In this tutorial, I used sorted lists because they make it easier to understand the relationship between the values ​​returned by different functions and the input data.

The above is the detailed content of Mathematical Modules in Python: Statistics. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles