Calculating Mean, Median, and Mode in Python

mode in python assignment expert

  • Introduction

When we're trying to describe and summarize a sample of data, we probably start by finding the mean (or average), the median , and the mode of the data. These are central tendency measures and are often our first look at a dataset.

In this tutorial, we'll learn how to find or compute the mean, the median, and the mode in Python. We'll first code a Python function for each measure followed by using Python's statistics module to accomplish the same task.

With this knowledge, we'll be able to take a quick look at our datasets and get an idea of the general tendency of data.

  • Calculating the Mean of a Sample

If we have a sample of numeric values, then its mean or the average is the total sum of the values (or observations) divided by the number of values.

Say we have the sample [4, 8, 6, 5, 3, 2, 8, 9, 2, 5] . We can calculate its mean by performing the operation:

(4 + 8 + 6 + 5 + 3 + 2 + 8 + 9 + 2 + 5) / 10 = 5.2

The mean (arithmetic mean) is a general description of our data. Suppose you buy 10 pounds of tomatoes. When you count the tomatoes at home, you get 25 tomatoes. In this case, you can say that the average weight of a tomato is 0.4 pounds. That would be a good description of your tomatoes.

The mean can also be a poor description of a sample of data. Say you're analyzing a group of dogs. If you take the cumulated weight of all dogs and divide it by the number of dogs, then that would probably be a poor description of the weight of an individual dog as different breeds of dogs can have vastly different sizes and weights.

How good or how bad the mean describes a sample depends on how spread the data is. In the case of tomatoes, they're almost the same weight each and the mean is a good description of them. In the case of dogs, there is no topical dog. They can range from a tiny Chihuahua to a giant German Mastiff. So, the mean by itself isn't a good description in this case.

Now it's time to get into action and learn how we can calculate the mean using Python.

  • Calculating the Mean With Python

To calculate the mean of a sample of numeric data, we'll use two of Python's built-in functions. One to calculate the total sum of the values and another to calculate the length of the sample.

The first function is sum() . This built-in function takes an iterable of numeric values and returns their total sum.

The second function is len() . This built-in function returns the length of an object. len() can take sequences (string, bytes, tuple, list, or range) or collections (dictionary, set, or frozen set) as an argument.

Here's how we can calculate the mean:

We first sum the values in sample using sum() . Then, we divide that sum by the length of sample , which is the resulting value of len(sample) .

  • Using Python's mean()

Since calculating the mean is a common operation, Python includes this functionality in the statistics module. It provides some functions for calculating basic statistics on sets of data. The statistics.mean() function takes a sample of numeric data (any iterable) and returns its mean.

Here's how Python's mean() works:

We just need to import the statistics module and then call mean() with our sample as an argument. That will return the mean of the sample. This is a quick way of finding the mean using Python.

  • Finding the Median of a Sample

The median of a sample of numeric data is the value that lies in the middle when we sort the data. The data may be sorted in ascending or descending order, the median remains the same.

To find the median, we need to:

  • Sort the sample
  • Locate the value in the middle of the sorted sample

When locating the number in the middle of a sorted sample, we can face two kinds of situations:

  • If the sample has an odd number of observations , then the middle value in the sorted sample is the median
  • If the sample has an even number of observations , then we'll need to calculate the mean of the two middle values in the sorted sample

If we have the sample [3, 5, 1, 4, 2] and want to find its median, then we first sort the sample to [1, 2, 3, 4, 5] . The median would be 3 since that's the value in the middle.

On the other hand, if we have the sample [1, 2, 3, 4, 5, 6] , then its median will be (3 + 4) / 2 = 3.5 .

Let's take a look at how we can use Python to calculate the median.

  • Finding the Median With Python

To find the median, we first need to sort the values in our sample . We can achieve that using the built-in sorted() function. sorted() takes an iterable and returns a sorted list containing the same values of the original iterable.

The second step is to locate the value that lies in the middle of the sorted sample. To locate that value in a sample with an odd number of observations, we can divide the number of observations by 2. The result will be the index of the value in the middle of the sorted sample.

Since a division operator ( / ) returns a float number, we'll need to use a floor division operator, ( // ) to get an integer. So, we can use it as an index in an indexing operation ( [] ).

If the sample has an even number of observations, then we need to locate the two middle values. Say we have the sample [1, 2, 3, 4, 5, 6] . If we divide its length ( 6 ) by 2 using a floor division, then we get 3 . That's the index of our upper-middle value ( 4 ). To find the index of our lower-middle value ( 3 ), we can decrement the index of the upper-middle value by 1 .

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Let's put all these together in a function that calculates the median of a sample. Here's a possible implementation:

This function takes a sample of numeric values and returns its median. We first find the length of the sample, n . Then, we calculate the index of the middle value (or upper-middle value) by dividing n by 2 .

The if statement checks if the sample at hand has an odd number of observations. If so, then the median is the value at index .

The final return runs if the sample has an even number of observations. In that case, we find the median by calculating the mean of the two middle values.

Note that the slicing operation [index - 1:index + 1] gets two values. The value at index - 1 and the value at index because slicing operations exclude the value at the final index ( index + 1 ).

  • Using Python's median()

Python's statistics.median() takes a sample of data and returns its median. Here's how the method works:

Note that median() automatically handles the calculation of the median for samples with either an odd or an even number of observations.

  • Finding the Mode of a Sample

The mode is the most frequent observation (or observations) in a sample. If we have the sample [4, 1, 2, 2, 3, 5] , then its mode is 2 because 2 appears two times in the sample whereas the other elements only appear once.

The mode doesn't have to be unique. Some samples have more than one mode. Say we have the sample [4, 1, 2, 2, 3, 5, 4] . This sample has two modes - 2 and 4 because they're the values that appear more often and both appear the same number of times.

The mode is commonly used for categorical data. Common categorical data types are:

  • boolean - Can take only two values like in true or false , male or female
  • nominal - Can take more than two values like in American - European - Asian - African
  • ordinal - Can take more than two values but the values have a logical order like in few - some - many

When we're analyzing a dataset of categorical data, we can use the mode to know which category is the most common in our data.

We can find samples that don't have a mode. If all the observations are unique (there aren't repeated observations), then your sample won't have a mode.

Now that we know the basics about mode, let's take a look at how we can find it using Python.

  • Finding the Mode with Python

To find the mode with Python, we'll start by counting the number of occurrences of each value in the sample at hand. Then, we'll get the value(s) with a higher number of occurrences.

Since counting objects is a common operation, Python provides the collections.Counter class. This class is specially designed for counting objects.

The Counter class provides a method defined as .most_common([n]) . This method returns a list of two-items tuples with the n more common elements and their respective counts. If n is omitted or None , then .most_common() returns all of the elements.

Let's use Counter and .most_common() to code a function that takes a sample of data and returns its mode.

Here's a possible implementation:

We first count the observations in the sample using a Counter object ( c ). Then, we use a list comprehension to create a list containing the observations that appear the same number of times in the sample.

Since .most_common(1) returns a list with one tuple of the form (observation, count) , we need to get the observation at index 0 in the list and then the item at index 1 in the nested tuple . This can be done with the expression c.most_common(1)[0][1] . That value is the first mode of our sample.

Note that the comprehension's condition compares the count of each observation ( v ) with the count of the most common observation ( c.most_common(1)[0][1] ). This will allow us to get multiple observations ( k ) with the same count in the case of a multi-mode sample.

  • Using Python's mode()

Python's statistics.mode() takes some data and returns its (first) mode. Let's see how we can use it:

With a single-mode sample, Python's mode() returns the most common value, 2 . However, in the preceding two examples, it returned 4 and few . These samples had other elements occurring the same number of times, but they weren't included.

Since Python 3.8 we can also use statistics.multimode() which accepts an iterable and returns a list of modes.

Here's an example of how to use multimode() :

Note: The function always returns a list , even if you pass a single-mode sample.

The mean (or average), the median, and the mode are commonly our first looks at a sample of data when we're trying to understand the central tendency of the data.

In this tutorial, we've learned how to find or compute the mean, the median, and the mode using Python. We first covered, step-by-step, how to create our own functions to compute them, and then how to use Python's statistics module as a quick way to find these measures.

You might also like...

  • Covariance and Correlation in Python
  • Calculating Spearman's Rank Correlation Coefficient in Python with Pandas
  • Change Tick Frequency in Matplotlib
  • Plotly Bar Plot - Tutorial and Examples

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Leodanis is an industrial engineer who loves Python and software development. He is a self-taught Python programmer with 5+ years of experience building desktop applications with PyQt.

In this article

mode in python assignment expert

Bank Note Fraud Detection with SVMs in Python with Scikit-Learn

Can you tell the difference between a real and a fraud bank note? Probably! Can you do it for 1000 bank notes? Probably! But it...

David Landup

Data Visualization in Python with Matplotlib and Pandas

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

© 2013- 2024 Stack Abuse. All rights reserved.

How to Calculate Mean, Median, Mode and Range in Python

mode in python assignment expert

John on October 07, 2020

mode in python assignment expert

When working with collections of data in Python we may want to find their mean median or mode. This can provide useful insights into what is happening inside a particular dataset or to compare it with other datasets.

In this tutorial, we will learn how to calculate the mean, median, and mode of iterable data types such as lists and tuples to discover more about them in Python.

Calculating the Mean

The mean is the result of all the values added together divided by the number of values. This will give us a generalised average of the data, which won't necessarily be a value located in the data. Let's say we had the following list of numbers and we wanted to find their mean:

We could approach this by adding the numbers together using a for loop and then dividing that by the length of the list . A better approach would be to use the built-in Python sum() function to get the sum of all the values in the list then divide that by the list length using the len() function.

In the above example, the mean is returned as a floating-point number. To round it to the nearest integer, use the Python round() function.

The Python mean() Method

If you need to calculate means often it might be worth importing the statistics package. It has a mean() method which will do all the work of calculating a mean from the data allowing your code to be cleaner.

Calculating the Median

The median is the middle number of a sorted collection of numbers. To get the median in Python we will first have to sort the iterable and then find the index in the centre by dividing the length of the list in half. If the centre index is odd we will have to get the average of the middle two numbers to get the median.

Let's create a function that will accept an iterable as an argument and return the median.

Inside the get_median() function above we are firstly sorting the input list using sorted() and getting the list length using len() . Then we are getting the centre index by getting length -1 (because indexes start at 0 ) and dividing that by 2 using the floor division operator ( // ) to ensure we get an integer.

Then, if the centre index is even the value of the index is returned, else the average of the two closest values to the centre is returned. This is done by adding index -1 to index +1 and dividing the result by 2 .

The Python median() method

We can get the median of an iterable on one line by using the statistics.median() method. This might be a better solution as all the work of odd centre index values is done for you.

Calculating the Mode

The mode is the most frequently occurring value in a collection of data. This principle can be applied to both numbers and strings. The mode could be a single value, multiple values or nothing if all the values are used equally. 

To get the number of times each value in a list occurred we can use the Counter() function from the collections package. Let's test it out on a list of numbers and print the result.

Counter() returns a class containing an ordered dictionary of each number and the number of times it occurred. We can then convert that into an list of tuples using the most_common() method. To get the highest occurring value select the first tuple using data.most_common(1) .

This isn't particularly useful because in the above example we can see that the values 4 and 6 both occurred 3 three times yet 4 was only shown as being the mode. To get all the mode values we can use list comprehension to build a new list and add items that are equally the highest occurring.

The Python mode() method

The statistics package provides a median() method, though it will only show one mode.

The Python multimode() method

The Python statistics.multimode() method will return a list of modes.

Calculating the Range

To get the range of values from a list we can use the min() and max() functions.

You now know how to get the mean, median, mode and range of values in Python. The statistics package pretty much has all bases covered when it comes to getting average, though it is good practice to know how to get them yourself first.

Related Tutorials

 thumbnail

Useful Vim Commands for Navigating, Editing & Searching Files

 thumbnail

How to Create Users in Linux Using the useradd Command

 thumbnail

How to Repeat N Times in Python

 thumbnail

How to Use Argparse in Python

 thumbnail

How to Create and Use Lists (Arrays) in Python

 thumbnail

How to Read CSV Files in Python

Calculate mean, median, mode, variance, standard deviation in Python

The Python statistics module provides various statistical operations, such as the computation of mean, median, mode, variance, and standard deviation.

  • statistics — Mathematical statistics functions — Python 3.11.4 documentation

Mean (arithmetic mean): statistics.mean()

Median: statistics.median() , statistics.median_low() , statistics.median_high(), mode: statistics.mode() , statistics.multimode(), population variance: statistics.pvariance(), sample variance: statistics.variance(), population standard deviation: statistics.pstdev(), sample standard deviation: statistics.stdev().

This article does not cover all functions of the module, like the calculation of harmonic and geometric means. Refer to the official documentation linked above for more information.

Although separate installation is required, using NumPy allows for operations on rows and columns of two-dimensional arrays, among other functionalities.

  • NumPy: Sum, mean, max, min for entire array, column/row-wise

The sample code in this article uses the statistics and math modules. Both are included in the standard library and do not require additional installation.

statistics.mean() calculates the arithmetic mean, which is the sum of elements divided by their count. It accepts iterable objects, such as lists and tuples, as arguments. The same applies to the functions presented in the following sections.

  • statistics.mean — Mathematical statistics functions — Python 3.11.4 documentation

You can calculate the mean using the built-in functions, sum() and len() .

statistics.median() , statistics.median_low() , and statistics.median_high() find the median, the middle value when the data is sorted. It's important to note that the data doesn't need to be sorted beforehand.

  • statistics.median() — Mathematical statistics functions — Python 3.11.4 documentation
  • statistics.median_low() — Mathematical statistics functions — Python 3.11.4 documentation
  • statistics.median_high() — Mathematical statistics functions — Python 3.11.4 documentation

If the number of data points is odd, all three functions return the middle value directly.

If the number of data points is even, statistics.median() returns the arithmetic mean of the two middle values, statistics.median_low() returns the smaller value, and statistics.median_high() returns the larger value.

You can use the built-in sorted() function and the sort() method of lists for sorting your data.

  • Sort a list, string, tuple in Python (sort, sorted)

statistics.mode() and statistics.multimode() allow you to find the mode, which is the most frequently occurring value.

  • statistics.mode() — Mathematical statistics functions — Python 3.11.4 documentation
  • statistics.multimode() — Mathematical statistics functions — Python 3.11.4 documentation

statistics.multimode() always returns the modes as a list, even if there is only one.

If multiple modes exist, statistics.mode() returns the first one.

You can use the Counter class from the collections module to count the frequency of each element and sort them accordingly.

  • Count elements in a list with collections.Counter in Python

statistics.pvariance() computes the population variance, which is the appropriate measure when the data represents the entire population.

  • statistics.pvariance() — Mathematical statistics functions — Python 3.11.4 documentation

The population variance $\sigma^2$ is calculated as follows for a population consisting of $n$ data points with mean $\mu$.

$$ \sigma^2=\frac{1}{n} \sum_{i=1}^{n} (x_i-\mu)^2 $$

By default, the mean is automatically calculated. However, the optional second argument, mu , allows you to specify the mean value directly. For example, if you've already calculated the mean, providing it through mu can help avoid recalculations.

You can calculate this using the built-in functions, sum() and len() .

A generator expression is passed to sum() .

  • List comprehensions in Python

statistics.variance() computes the sample variance, which is the appropriate measure when the data is a sample from a larger population.

  • statistics.variance() — Mathematical statistics functions — Python 3.11.4 documentation

This method specifically calculates the unbiased sample variance where the denominator is $n-1$, not $n$. This adjustment to the denominator, known as Bessel's correction, helps to correct the bias in the estimation of the population variance from a sample.

The unbiased sample variance $s^2$ is calculated as follows for a sample of $n$ data points from the population with mean $\overline{x}$.

$$ s^2=\frac{1}{n-1} \sum_{i=1}^{n} (x_i-\overline{x})^2 $$

By default, the mean is automatically calculated. However, the optional second argument, xbar , allows you to specify the mean value directly. For example, if you've already calculated the mean of the sample, providing it through xbar can help avoid recalculations.

Standard deviation

statistics.pstdev() returns the population standard deviation.

  • statistics.pstdev() — Mathematical statistics functions — Python 3.11.4 documentation

The population standard deviation is the square root of the population variance.

statistics.stdev() returns the sample standard deviation.

  • statistics.stdev — Mathematical statistics functions — Python 3.11.4 documentation

The sample standard deviation is the square root of the sample variance.

Related Categories

  • Mathematics

Related Articles

  • Trigonometric functions in Python (sin, cos, tan, arcsin, arccos, arctan)
  • Complex numbers in Python
  • NumPy: Trigonometric functions (sin, cos, tan, arcsin, arccos, arctan)
  • Matrix operations with NumPy in Python
  • Fractions (rational numbers) in Python
  • Power and logarithmic functions in Python (exp, log, log10, log2)
  • Find GCD and LCM in Python (math.gcd(), lcm())
  • Set operations in Python (union, intersection, symmetric difference, etc.)
  • NumPy: Create an empty array (np.empty, np.empty_like)
  • pandas: Grouping data with groupby()
  • Copy a file/directory in Python (shutil.copy, shutil.copytree)
  • Replace strings in Python (replace, translate, re.sub, re.subn)
  • Image processing with Python, NumPy
  • pandas: Shuffle rows/elements of DataFrame/Series

pythoneo

Online How to Python stuff

How to calculate mode in Python?

Let’s see how to calculate mode in Python.

mode python

Mode in Python

To calculate the mode, we need to import the statistics module.

Luckily, there is dedicated function in statistics module to calculate mode.

Mode in Numpy

It was how to calculate mode in Python. However, calculating the mode directly with NumPy requires a workaround since NumPy does not have a built-in mode function.

Thanks to this mode = np.argmax(np.bincount(my_array)) easy trick mode has been calculated.

Numpy mode calculations

How to calculate the mode of an array in NumPy?

In addition to using the statistics module to calculate the mode of a list in Python, you can also use the np.argmax and np.bincount functions in NumPy. The np.argmax function takes an array as a parameter and returns the index of the element with the maximum value. The np.bincount function takes an array as a parameter and returns a count of the number of times each element appears in the array.

To calculate the mode of an array in NumPy, you can use the following code:

This code will print the following output:

As you can see, the mode of the array my_array is 7. This is because the element 7 appears more often than any other element in the array.

CodexCoach

  • Get Started
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If … Else
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python Classes and Objects
  • Python Inheritance
  • Python Iterators
  • Python Polymorphism
  • Python Scope
  • Python Modules
  • Python Math
  • Python JSON
  • Python RegEx
  • Python Try Except
  • Python User Input
  • Python String Formatting
  • Python Datetime
  • Python read files
  • Python write/create files
  • Python delete files
  • Matplotlib Get Started
  • Matplotlib Pyplot
  • Matplotlib Plotting
  • Matplotlib Markers
  • Matplotlib Line
  • Matplotlib Labels and Title
  • Matplotlib Subplot
  • Matplotlib Scatter
  • Matplotlib Bars
  • Matplotlib Histograms
  • Matplotlib Pie Charts
  • Matplotlib Adding Grid Lines

Mean, Median, and Mode

  • Standard Deviation
  • Percentiles
  • Data Distribution
  • Normal Data Distribution
  • Scatter Plot
  • Linear Regression
  • Polynomial Regression
  • Multiple Regression
  • Decision Tree
  • Confusion Matrix
  • Hierarchical Clustering
  • Logistic Regression
  • Grid Search
  • Categorical Data
  • Bootstrap Aggregation
  • Cross Validation
  • AUC – ROC Curve
  • K-nearest neighbors
  • Python MySQL Create Database
  • Python MySQL Create Table
  • Python MySQL Insert Into Table
  • Python MySQL Select From
  • Python MySQL Where
  • Python MySQL Order By
  • Python MySQL Delete From By
  • Python MySQL Drop Table
  • Python MySQL Update Table
  • Python MySQL Limit
  • Python MySQL Join
  • MongoDB Create Database
  • MongoDB Create Collection
  • MongoDB Insert Document
  • MongoDB Find
  • MongoDB Query
  • MongoDB Sort
  • MongoDB Delete Document
  • MongoDB Drop Collection
  • MongoDB Update
  • MongoDB Limit
  • Python Built in Functions
  • Python String Methods
  • Python List/Array Methods
  • Python Dictionary Methods
  • Python Tuple Methods
  • Python Set Methods
  • Python File Methods
  • Python Keywords
  • Python Built-in Exceptions
  • Python Glossary
  • Python Random Module
  • Python Requests Module
  • Python statistics Module
  • Python math Module
  • Python cmath Module

Understanding Mean, Median, and Mode in Statistics

If you’re delving into the realm of data analysis and statistics, you’ll inevitably encounter three fundamental concepts: Mean, Median, and Mode. These statistical measures provide valuable insights into data distribution and central tendency. In this expert guide, we’ll demystify these concepts and illustrate them with Python examples to deepen your understanding.

Mean , often referred to as the “average,” is a central measure of a dataset. It is calculated by summing up all values in a dataset and then dividing by the total number of data points. The formula for calculating the mean of a dataset with n data points is:

Here, Σ(x) represents the sum of all data points.

Example: Suppose you have a list of test scores: [85, 92, 78, 95, 88] . To find the mean score, sum all the values and divide by the number of scores:

So, the mean test score is 87.6.

The median is the middle value of a dataset when it’s arranged in ascending or descending order. If there’s an even number of data points, the median is the average of the two middle values. In a dataset with n data points:

  • If n is odd, the median is the value at position (n+1)/2 .
  • If n is even, the median is the average of the values at positions n/2 and (n/2) + 1 .

Example: Consider the dataset: [12, 45, 67, 23, 98, 54] . When arranged in ascending order, it becomes: [12, 23, 45, 54, 67, 98] . Since there are 6 data points (even), the median is the average of the values at positions 3 and 4:

So, the median of the dataset is 49.5.

The mode is the value that appears most frequently in a dataset. A dataset can have one mode (unimodal), more than one mode (multimodal), or no mode at all if all values occur with the same frequency.

Example: In the dataset [5, 7, 8, 2, 7, 5, 8, 3, 7] , the number 7 appears most frequently (three times). Therefore, the mode of this dataset is 7 .

Python Examples

Let’s put these concepts into action with Python code examples:

Mean Calculation in Python

Median calculation in python, mode calculation in python.

By mastering these statistical measures, you’ll be better equipped to analyze and interpret data, a crucial skill in the world of Python programming and data science. Happy learning!

Never miss a drop!

logo

Stay Connected for All New Things

My Tec Bits

How to calculate Mean, Median and Mode in Python?

In my earlier articles, we have see calculating mean, median and mode in SQL Server and C#.NET . Unlike SQL Server and .NET, Python programming language has an inbuilt module called statistics which has some basic mathematical statistics functions including mean, median and mode. This statistics module was introduced in Python version 3.4.

The statistics module has multiple functions. Below are the functions which calculate mean, median and mode.

  • mean() : To get the arithmetic mean of the given set of data. Arithmetic mean is also the average of the data.
  • median() : To get the median or the middle value of the given set of data.
  • mode() : To get the single mode of the given set of data. If there are multiple modes in the data, then this function returns the first mode it identifies.
  • multimode() : Lists all the modes in the given set of data. If there is no mode, then this function will return all the elements of the data.

Here is the sample code to find mean, median and mode in Python using the statistics module.

  • Read more about Python’s statistics module at Python Docs .
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to print (Opens in new window)

You may also like...

Leave your thoughts... cancel reply.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Adventures in Machine Learning

Mastering data analysis in pandas: mean median and mode.

Data analysis is an essential skill for anyone working with data. In particular, analyzing data in Pandas can be an efficient way to manage and manipulate large datasets.

One important aspect of data analysis is calculating the mean, median, and mode of numerical data. In this article, we’ll look at the functions available in Pandas for calculating these statistical measures and how they are applied in the context of basketball player data.

Data Analysis in Pandas

Pandas is a Python library specifically developed for data manipulation and analysis. It provides features for handling different types of data such as DataFrame, Series and Panel, and is particularly useful in handling large datasets.

Pandas provides functions for many statistical measures, including mean, median, and mode. The mean of a set of numerical data is the average value.

It is calculated by adding up all the values in the dataset and dividing by the number of observations. Pandas provides the function “mean()” that calculates the mean of each column in a DataFrame.

This function can be used to quickly calculate the average value of specific numerical data. The median is the middle value in a sorted dataset, with an equal number of values above and below it.

While not as commonly used as the mean, it can be useful in certain cases. The function “median()” in Pandas calculates the median for each column in a DataFrame.

The mode is the value that appears most frequently in a dataset. The mode can be useful for examining the most common occurrence of a value within a dataset.

Pandas provides the “mode()” function to calculate the mode for each column in a DataFrame. Example of calculating mean, median, and mode for basketball player data

Let’s apply these statistical functions to basketball player data.

We will use a dataset that includes information for basketball players for a number of games. The data includes each player’s points per game, rebounds per game, and minutes per game.

To calculate the mean, median, and mode of the dataset, we can use the following syntax:

import pandas as pd

data = pd.read_csv(“basketball_players.csv”)

# calculate mean

mean_scores = data.mean()

print(“Mean scores: n”, mean_scores)

# calculate median

median_scores = data.median()

print(“Median scores: n”, median_scores)

# calculate mode

mode_scores = data.mode()

print(“Mode scores: n”, mode_scores)

The output will display the calculated mean, median, and mode for each column in the dataset, as shown below:

Mean scores:

dtype: float64

Median scores:

Mode scores:.

PPG RPG MPG

0 8.0 3.5 16.0

From the output, we can see that the mean number of points per game is 10.80, the median number of points per game is 10.5, and the mode number of points per game is 8.

Mean Calculation in Pandas

The “mean()” function in Pandas calculates the mean of each column in a DataFrame. However, it is important to note that this function will only work on columns with numerical data.

It will ignore any strings or non-numerical data. Here is an example of calculating the mean of specific columns in a dataset using Pandas:

# calculate mean of points per game

mean_points = data[‘PPG’].mean()

print(“Mean points per game: “, mean_points)

# calculate mean of minutes per game

mean_minutes = data[‘MPG’].mean()

print(“Mean minutes per game: “, mean_minutes)

The output will display the mean value for each specific column, as shown below:

Mean points per game: 10.8

Mean minutes per game: 17.04

Output examples for mean value calculation

In addition to displaying the calculated mean result, we can use the functions “describe()” and “info()” to provide additional information about the data. The “describe()” function provides statistical information on each column, such as the count, mean, standard deviation, minimum value, and maximum value.

Here is an example of using Pandas to calculate the mean of each column and provide a statistical summary of the data:

# provide additional information

print(“nSummary statistics:”)

print(data.describe())

The output will display the mean value for each column as well as statistical information on each column, as shown below:

Summary statistics:

count 10.000000 10.000000 10.000000

mean 10.800000 4.140000 17.040000

std 3.371396 1.845898 3.400396

min 5.000000 1.700000 12.000000

25% 9.125000 3.175000 15.925000

50% 10.500000 3.700000 17.500000

75% 12.750000 5.075000 20.225000

max 15.000000 7.700000 22.000000

In this article, we have discussed the basics of data analysis in Pandas, specifically focusing on calculating the mean, median, and mode of numeric data. These functions are crucial for understanding and interpreting numerical data, and can be used in a variety of different contexts.

By following the examples provided, you should be able to begin working with these functions yourself and conducting your own data analysis in Pandas.

3) Median Calculation in Pandas

In statistics, the median is the middle value in a dataset when the data is arranged in ascending or descending order. It is a statistical measure used to represent the midpoint value of a set of data, which avoids issues with outliers that can affect the accuracy of the mean.

In Pandas, the “median()” function can be used to calculate the median of each column in a DataFrame.

Syntax for calculating median of numeric columns in a DataFrame

To calculate the median value of numeric columns in a DataFrame, we can use the “median()” function in Pandas. The syntax for using this function is as follows:

data = pd.read_csv(“example_data.csv”)

median_values = data.median()

print(“Median values: n”, median_values)

In this example, we first import the Pandas library and then read in a CSV file containing our data. We then use the “median()” function to calculate the median value of each column in the DataFrame.

Finally, we use the “print()” function to display the median values calculated.

Output examples for median value calculation

The median value calculated by the “median()” function is an important summary statistic that helps us understand the central tendency of our data. In combination with other statistics such as mean and standard deviation, the median can provide a more accurate representation of the distribution of our data.

Here is an example of using Pandas to calculate the median of each column in a dataset:

median_data = data.median()

# display output

print(“Median Values of the Data:n”, median_data)

The output for the above code block will be as follows:

Median values of the data:.

Here we can see that the median value of column A is 25.5, the median value of column B is 24.5, the median value of column C is 15.5, and the median value of column D is 25.0.

4) Mode Calculation in Pandas

The mode is a statistical measure that represents the most commonly occurring value in a dataset. The mode is the value that appears most frequently in a set of data, making it an essential tool in understanding the underlying distribution of the data.

Pandas provides the “mode()” function to calculate the mode of each column in a DataFrame.

Syntax for calculating mode of numeric columns in a DataFrame

To calculate the mode of numeric columns in a DataFrame, we can use the “mode()” function in Pandas. The syntax for using this function is as follows:

mode_values = data.mode()

print(“Mode values: n”, mode_values)

In this example, we first import the Pandas library and then read in a CSV file containing our data. We then use the “mode()” function to calculate the mode of each column in the DataFrame.

Finally, we use the “print()” function to display the mode values calculated.

Output examples for mode value calculation

Like median and mean, the mode can provide important information about the central tendency of our data. By calculating the mode of our data, we can identify the most frequently occurring values or patterns in our dataset, which can be useful in understanding and predicting future trends.

Here is an example of using Pandas to calculate the mode of each column in a dataset:

mode_data = data.mode()

print(“Mode Values of the Data:n”, mode_data)

Mode Values of the Data:

0 23 10 2 14, 1 24 23 6 25.

Here we can see that the mode value of column A is either 23 or 24, the mode value of column B is either 10 or 23, the mode value of column C is either 2 or 6, and the mode value of column D is either 14 or 25. Since there can be multiple modes in a dataset, Pandas displays all possible modes in the output as a DataFrame.

Data analysis is a critical skill that can help uncover valuable insights and make informed decisions. In this article, we explored the syntax and output examples for calculating the median and mode of numeric columns in a DataFrame using Pandas.

Understanding these statistical measures can help us gain a deeper understanding of the underlying distribution of our data, and can be used to identify trends and patterns that may be hidden within the data. By using the examples and syntax provided in this article, you can begin to apply these tools in your own data analysis projects.

5) Additional Resources for Pandas

Pandas is a versatile library that provides a wide range of functions for manipulating and analyzing data in Python. In addition to calculating mean, median, and mode, there are many other commonly used operations that can be performed using Pandas.

Here, we will explore some of these operations and provide additional resources for learning more about working with Pandas.

Explanation of other common operations in Pandas

1. Handling Missing Data – Missing data is common in real-world datasets.

Pandas provides functions for identifying and handling missing data, such as the “isna()” and “dropna()” functions. 2.

Grouping Data – Grouping data is a powerful operation that allows you to create subsets of your data based on one or more criteria. Pandas provides the “groupby()” function for grouping data based on specific columns.

3. Merging and Joining Data – Often, data is split across multiple files or tables.

Pandas provides functions such as “merge()” and “join()” to combine data from multiple sources. 4.

Reshaping Data – Sometimes you may need to reshape your data to better fit your analysis. Pandas provides functions for pivoting data (for example, converting row data to column data) and “melting” data (for example, combining multiple columns into one).

5. Applying Functions to Data – Often, you may need to apply a custom function to your data.

Pandas provides the “apply()” function for applying a given function to each element in a DataFrame. 6.

Working with Time Series Data – Pandas has extensive capabilities for working with time series data. This includes functions for handling dates and times and for creating time-based subsets of data.

Tutorials and Additional Resources

There are a variety of resources available for learning more about Pandas. The official Pandas documentation is an excellent place to start.

It provides detailed documentation on all of the functions and features of the library, as well as numerous examples and tutorials. For those new to Pandas, there are many online tutorials available.

Some popular options include:

1. Pandas Documentation – The official documentation provides a wide range of tutorials and examples.

2. DataCamp – DataCamp provides a comprehensive Pandas course that covers everything from simple data operations to more advanced data wrangling.

3. Kaggle – Kaggle offers a variety of Pandas tutorials and notebooks, as well as datasets to practice with.

4. RealPython – RealPython provides a beginner-friendly introduction to Pandas, with step-by-step instructions and clear examples.

5. YouTube – YouTube has many tutorials available for Pandas, from beginner to advanced levels.

Some popular channels include Corey Schafer and Keith Galli. In addition to these resources, Pandas has a large and active community, with many forums and discussion groups available for asking questions and seeking help.

Some popular options include the Pandas Google Group and the Stack Overflow Pandas tag.

Pandas is a powerful and versatile library that provides numerous functions for manipulating and analyzing data in Python. In addition to the basic statistical measures such as mean, median, and mode, there are many other common operations that can be performed using Pandas.

By exploring the tutorials and resources available and experimenting with different operations, you can become proficient in working with Pandas and find valuable insights in your data. In summary, this article explored the basics of data analysis in Pandas, focusing on calculating the mean, median, and mode of numeric data.

We also covered additional common operations in Pandas, such as handling missing data, merging and joining data, grouping data, and reshaping data. Finally, we provided additional resources and tutorials for learning more about working with Pandas.

It is important to understand these statistical measures and common operations in order to gain a deeper understanding of the underlying distribution of data and uncover valuable insights. By following the examples and utilizing the resources provided, readers can become proficient in working with Pandas and improve their data analysis skills.

Popular Posts

Unleashing the power of data analysts: the driving force behind informed decision-making, mastering the python return statement: functions behavior and usage, mastering pandas: 3 ways to remove a column from a python dataframe.

  • Terms & Conditions
  • Privacy Policy
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Python statistics | variance()
  • harmonic_mean() in Python
  • float() in Python
  • Python statistics | mean() function
  • Python | Counter Objects | elements()
  • degrees() and radians() in Python
  • Python - globals() function
  • dir() function in Python
  • Python hash() method
  • Modular Exponentiation in Python
  • Python math.sqrt() function | Find Square Root in Python
  • Python String isprintable() Method
  • __closure__ magic function in Python
  • Formatting containers using format() in Python
  • Python math function | hypot()
  • Python __add__() magic method
  • Python __len__() magic method
  • memoryview() in Python
  • Python len() Function

mode() function in Python statistics module

The mode of a set of data values is the value that appears most often . It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode. Python is very robust when it comes to statistics and working with a set of a large range of values. The statistics module has a very large number of functions to work with very large data-sets. The mode() function is one of such methods. This function returns the robust measure of a central data point in a given range of data-sets.

Example :  

Code #1 : This piece will demonstrate mode() function through a simple example. 

Code #2 : In this code we will be demonstrating the mode() function a various range of data-sets. 

Code #3 : In this piece of code will demonstrate when StatisticsError is raised 

Output 

NOTE: In newer versions of Python, like Python 3.8, the actual mathematical concept will be applied when there are multiple modes for a sequence, where, the smallest element is considered as a mode. Say, for the above code, the frequencies of -1 and 1 are the same, however, -1 will be the mode, because of its smaller value.

Applications: The mode() is a statistics function and mostly used in Financial Sectors to compare values/prices with past details, calculate/predict probable future prices from a price distribution set. mean() is not used separately but along with two other pillars of statistics mean and median creates a very powerful tool that can be used to reveal any aspect of your data.   

Please Login to comment...

Similar reads.

author

  • Python-Built-in-functions
  • 10 Ways to Use Microsoft OneNote for Note-Taking
  • 10 Best Yellow.ai Alternatives & Competitors in 2024
  • 10 Best Online Collaboration Tools 2024
  • 10 Best Autodesk Maya Alternatives for 3D Animation and Modeling in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • How it works
  • Homework answers

Physics help

Python Answers

Questions: 5 831

Answers by our Experts: 5 728

Ask Your question

Need a fast expert's response?

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS !

Search & Filtering

Create a method named check_angles. The sum of a triangle's three angles should return True if the sum is equal to 180, and False otherwise. The method should print whether the angles belong to a triangle or not.

11.1  Write methods to verify if the triangle is an acute triangle or obtuse triangle.

11.2  Create an instance of the triangle class and call all the defined methods.

11.3  Create three child classes of triangle class - isosceles_triangle, right_triangle and equilateral_triangle.

11.4  Define methods which check for their properties.

Create an empty dictionary called Car_0 . Then fill the dictionary with Keys : color , speed , X_position and Y_position.

car_0 = {'x_position': 10, 'y_position': 72, 'speed': 'medium'} .

a) If the speed is slow the coordinates of the X_pos get incremented by 2.

b) If the speed is Medium the coordinates of the X_pos gets incremented by 9

c) Now if the speed is Fast the coordinates of the X_pos gets incremented by 22.

Print the modified dictionary.

Create a simple Card game in which there are 8 cards which are randomly chosen from a deck. The first card is shown face up. The game asks the player to predict whether the next card in the selection will have a higher or lower value than the currently showing card.

For example, say the card that’s shown is a 3. The player chooses “higher,” and the next card is shown. If that card has a higher value, the player is correct. In this example, if the player had chosen “lower,” they would have been incorrect. If the player guesses correctly, they get 20 points. If they choose incorrectly, they lose 15 points. If the next card to be turned over has the same value as the previous card, the player is incorrect.

Consider an ongoing test cricket series. Following are the names of the players and their scores in the test1 and 2.

Test Match 1 :

Dhoni : 56 , Balaji : 94

Test Match 2 :

Balaji : 80 , Dravid : 105

Calculate the highest number of runs scored by an individual cricketer in both of the matches. Create a python function Max_Score (M) that reads a dictionary M that recognizes the player with the highest total score. This function will return ( Top player , Total Score ) . You can consider the Top player as String who is the highest scorer and Top score as Integer .

Input : Max_Score({‘test1’:{‘Dhoni’:56, ‘Balaji : 85}, ‘test2’:{‘Dhoni’ 87, ‘Balaji’’:200}}) Output : (‘Balaji ‘ , 200)

Write a Python program to demonstrate Polymorphism.

1. Class  Vehicle  with a parameterized function  Fare,  that takes input value as fare and

returns it to calling Objects.

2. Create five separate variables  Bus, Car, Train, Truck and Ship  that call the  Fare

3. Use a third variable  TotalFare  to store the sum of fare for each Vehicle Type. 4. Print the  TotalFare.

Write a Python program to demonstrate multiple inheritance.

1.  Employee  class has 3 data members  EmployeeID ,  Gender  (String) , Salary  and

PerformanceRating ( Out of 5 )  of type int. It has a get() function to get these details from

2.  JoiningDetail  class has a data member  DateOfJoining  of type  Date  and a function

getDoJ  to get the Date of joining of employees.

3.  Information  Class uses the marks from  Employee  class and the  DateOfJoining  date

from the  JoiningDetail  class to calculate the top 3 Employees based on their Ratings and then Display, using  readData , all the details on these employees in Ascending order of their Date Of Joining.

You are given an array of numbers as input: [10,20,10,40,50,45,30,70,5,20,45] and a target value: 50. You are required to find pairs of elements (indices of two numbers) from the given array whose sum equals a specific target number. Your solution should not use the same element twice, thus it must be a single solution for each input

1.1 Write a Python class that defines a function to find pairs which takes 2 parameters (input array and target value) and returns a list of pairs whose sum is equal to target given above. You are required to print the list of pairs and state how many pairs if found. Your solution should call the function to find pairs, then return a list of pairs.

1.2 Given the input array nums in 1.1 above. Write a second program to find a set of good pairs from that input array nums. Here a pair (i,j) is said to be a good pair if nums[i] is the same as nums[j] and i < j. You are required to display an array of good pairs indices and the number of good pairs.

How to find largest number inn list in python

Given a list of integers, write a program to print the sum of all prime numbers in the list of integers.

Note: one is neither prime nor composite number

Using the pass statement

how to get a input here ! example ! 2 4 5 6 7 8 2 4 5 2 3 8 how to get it?

  • Programming
  • Engineering

10 years of AssignmentExpert

IMAGES

  1. mean median and mode in python

    mode in python assignment expert

  2. Calculate Mode in Python (Example)

    mode in python assignment expert

  3. How to Find Mode in Python using Numpy array with Examples

    mode in python assignment expert

  4. Finding the Mode of a List in Python

    mode in python assignment expert

  5. Python For Beginners

    mode in python assignment expert

  6. Expert Python Tutorial #1

    mode in python assignment expert

VIDEO

  1. Assignment

  2. Mode in Python

  3. Interpreter mode Vs Script Mode| Python Programming |MACSGATE|Sridhar

  4. How to find mode in Python #interviewquestions #python #pythontutorial

  5. Execution Modes in Python

  6. "Mastering Assignment Operators in Python: A Comprehensive Guide"

COMMENTS

  1. Answer in Python for adhi chinna #179548

    Question #179548. Mean, Median and Mode. Given a list of integers, write a program to print the mean, median and mode. Mean - The average value of all the numbers. Median - The mid point value in the sorted list. Mode - The most common value in the list. If multiple elements with same frequency are present, print all the values with same ...

  2. Answer in Python for CHANDRASENA REDDY CHADA #179423

    Question #179423. Mean, Median and Mode. Given a list of integers, write a program to print the mean, median and mode. Mean - The average value of all the numbers. Median - The mid point value in the sorted list. Mode - The most common value in the list. If multiple elements with same frequency are present, print all the values with same ...

  3. Answer in Python for J NAGAMANI #186630

    Question #186630. Given a list of integers, write a program to print the mean, median and mode. Mean - The average value of all the numbers. Median - The mid point value in the sorted list. Mode - The most common value in the list. If multiple elements with same frequency are present, print all the values with same frequency in increasing order.

  4. Calculating Mean, Median, and Mode in Python

    Finding the Mode with Python. To find the mode with Python, we'll start by counting the number of occurrences of each value in the sample at hand. Then, we'll get the value(s) with a higher number of occurrences. Since counting objects is a common operation, Python provides the collections.Counter class. This class is specially designed for ...

  5. Finding Mean, Median, Mode in Python without libraries

    3. Mode : The mode is the number that occurs most often within a set of numbers. This code calculates Mode of a list containing numbers: We will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list.

  6. How to Find Mean, Median, and Mode in Python?

    Here's how you use this module: from statistics import mean. pythonic_machine_ages = [19, 22, 34, 26, 32, 30, 24, 24] print( mean ( pythonic_machine_ages)) In the above code, you just need to import the mean () function from the statistics module and pass the dataset to it as an argument.

  7. How to Calculate Mean, Median, Mode and Range in Python

    Calculating the Mode. The mode is the most frequently occurring value in a collection of data. This principle can be applied to both numbers and strings. The mode could be a single value, multiple values or nothing if all the values are used equally.

  8. Calculate mean, median, mode, variance, standard deviation in Python

    The population variance σ2 σ 2 is calculated as follows for a population consisting of n n data points with mean μ μ. σ2 = 1 n n ∑ i=1(xi −μ)2 σ 2 = 1 n ∑ i = 1 n ( x i − μ) 2. By default, the mean is automatically calculated. However, the optional second argument, mu, allows you to specify the mean value directly.

  9. How to calculate mode in Python?

    In addition to using the statistics module to calculate the mode of a list in Python, you can also use the np.argmax and np.bincount functions in NumPy. The np.argmax function takes an array as a parameter and returns the index of the element with the maximum value.

  10. Understanding Mean, Median, And Mode In Statistics With Python Examples

    Dive into the world of statistics as we explore the concepts of Mean, Median, and Mode with expert guidance and practical Python examples. Learn how to analyze and interpret data like a pro! ... Therefore, the mode of this dataset is 7. Python Examples. Let's put these concepts into action with Python code examples: Mean Calculation in Python ...

  11. Find the mode of a list of numbers in python

    mode = (value, i) modes.append(mode) counter += mode[1] # Create the counter that sums the number of most common occurrences. # Example [1, 2, 2, 3, 3] # 2 appears twice, 3 appears twice, [2, 3] are a mode. # because sum of counter for them: 2+2 != 5. if counter != len(l): return [mode[0] for mode in modes] else:

  12. Answer in Python for jayanth #179148

    Question #179148. Mean, Median and Mode. Given a list of integers, write a program to print the mean, median and mode. Mean - The average value of all the numbers. Median - The mid point value in the sorted list. Mode - The most common value in the list. If multiple elements with same frequency are present, print all the values with same ...

  13. Learn Statistics with Python: Mean, Median, and Mode Cheatsheet

    If there are an even number of values in a dataset, the middle two values are the median. Say we have a dataset with the following ten numbers: 24, 16, 30, 10, 12, 28, 38, 2, 4, 36. We can order this dataset from smallest to largest: 2, 4, 10, 12, 16, 24, 28, 30, 36, 38. The medians of this dataset are 16 and 24, because they are the fifth- and ...

  14. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  15. How to calculate Mean, Median and Mode in Python?

    median () : To get the median or the middle value of the given set of data. mode () : To get the single mode of the given set of data. If there are multiple modes in the data, then this function returns the first mode it identifies. multimode () : Lists all the modes in the given set of data. If there is no mode, then this function will return ...

  16. Mastering Data Analysis in Pandas: Mean Median and Mode

    Pandas is a Python library specifically developed for data manipulation and analysis. It provides features for handling different types of data such as DataFrame, Series and Panel, and is particularly useful in handling large datasets. Pandas provides functions for many statistical measures, including mean, median, and mode.

  17. Answer in Python for phani #179156

    Question #179156. Mean, Median and Mode. Given a list of integers, write a program to print the mean, median and mode. Mean - The average value of all the numbers. Median - The mid point value in the sorted list. Mode - The most common value in the list. If multiple elements with same frequency are present, print all the values with same frequency.

  18. mode() function in Python statistics module

    The mode of a set of data values is the value that appears most often.It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode. Python is very robust when it comes to statistics and working with a set of a large ...

  19. pandas

    You can groupy the 'ITEM' and 'CATEGORY' columns and then call apply on the df groupby object and pass the function mode. We can then call reset_index and pass param drop=True so that the multi-index is not added back as a column as you already have those columns: In [161]: df.groupby(['ITEM', 'CATEGORY']).apply(pd.DataFrame.mode).reset_index ...

  20. Mastering Python: A Guide to Writing Expert-Level Assignments

    Question 1: You are given a list of integers, and your task is to write a Python function to find the maximum product of two integers in the list. def max_product (nums): nums.sort () return max ...

  21. Answer in Python for suresh #184120

    Question #184120. Given a list of integers, write a program to print the mean, median and mode. Mean - The average value of all the numbers. Median - The mid point value in the sorted list. Mode - The most common value in the list. If multiple elements with same frequency are present, print all the values with same frequency in increasing order ...

  22. python

    If you worked in python with pandas you already know the chained_assignment warning when working on slices of dataframes (as e.g. described here ). I found the option pandas.options.mode.chained_assignment which can be set to. None, ignoring the warning. "warn", printing a warning message. "raise", raising an exception. compare with documentation.

  23. Python Answers

    Question #350996. Python. Create a method named check_angles. The sum of a triangle's three angles should return True if the sum is equal to 180, and False otherwise. The method should print whether the angles belong to a triangle or not. 11.1 Write methods to verify if the triangle is an acute triangle or obtuse triangle.