Python Tutorial 24 : Descriptive statistics in Python

Python support following Descriptive statistics  function

Averages and measures of the central location

mean()Arithmetic mean (“average”) of data.
harmonic_mean()Harmonic mean of data.
median()Median (middle value) of data.
median_low()Low median of data.
median_high()High median of data.
median_grouped()Median, or 50th percentile, of grouped data.
mode()Mode (most common value) of discrete data.

Measures of spread

pstdev()Population standard deviation of data.
pvariance()Population variance of data.
stdev()Sample standard deviation of data.
variance()Sample variance of data.

Following example illustrated how to use them

Descriptive statistics in Python

Following is the explanation to the function

  1. Define a list called temperature that stores some numbers for testing purposes only.
    [vtftable ]
    {f3}temperature = [10, 15, 30, 45,60,90];nn;
  2. Import the statistic library. All descriptive statistics are stored in this library. Therefore, we need to import this library before we can access to those functions[vtftable ]
    {f3}import statistics;nn;
  3. Print the mean of the list[vtftable ]
    {f3}print(“Mean:”, statistics.mean(temperature_list))nn;
  4. Print the Median of the list[vtftable ]
    {f3}print(“Median:”, statistics.median(temperature_list))nn;
  5. Print the Mode of the list.
    [vtftable ]
    try:{;n} print(“Mode:”, statistics.mode(temperature_list)){;n}except statistics.StatisticsError as e:{;n} print(“Mode Error:”,e);nn;
    [/vtftable]Note: This time we have used the “Try … except” statement to handle error Statistics Error as the mode function is looking for the number with the highest frequency. However, it is very common that a list have more the one numbers with the highest frequency. Without the “try .. except” error handling statement, it will crash the program.
  6. Print the Standard Deviation of the list[vtftable ]
    {f3}print(“Standard Deviation:”, statistics.stdev(temperature_list));nn;
  7. Print the Variance of the list[vtftable ]

Following is the result:

Descriptive statistics in Python - result

Leave a Comment