Hey, folks! In continuation of our series on Python statistical functions, today we will be unveiling standard deviation using the Python stdev() method.
Standard deviation is a statistical entity that represents the variation in the data i.e. it depicts the deviation of data values from the center value (the mean of the data).
Usually, standard deviation is calculated using the below formula–
Standard Deviation = (Variance)^1/2
Now, let us start with the implementation and calculation of Standard Deviation using Python in-built function.
Getting started with Python stdev() function
Python statistics module contains various in-built functions to perform the data analysis and other statistical functions. The
statistics.stdev() function is used to calculate the standard deviation of the passed data values to the function as argument.
import statistics data = range(1,10) res_std = statistics.stdev(data) print(res_std)
In the above example, we have created data of numbers from 1-10 using the range() function. Further, we apply the stdev() function to evaluate the standard deviation of the data values.
Python standard deviation with NumPy module
Python NumPy module converts the data elements into an array form to perform numeric manipulations on it.
numpy.std() function can be used to calculate the standard deviation of all the data values present in the NumPy array.
We need to import the NumPy module into the Python environment to get access to the in-built functions of the same using the below code–
import numpy as np import pandas as pd data = np.arange(1,30) res_std = np.std(data) print(res_std)
In the above example, we have generated an array of elements from 1-30 using
numpy.arange() function. After which, we pass the array to the
numpy.std() function to calculate the standard deviation of the array elements.
Python standard deviation with Pandas module
Python Pandas module converts the data values into a DataFrame and helps us analyse and work with huge datasets. The
pandas.DataFrame.std() function is used to calculate the standard deviation of the data column values of a particular DataFrame.
import numpy as np import pandas as pd data = np.arange(1,10) df = pd.DataFrame(data) res_std = df.std() print(res_std)
In the above example, we have converted a NumPy array into a DataFrame and the applied the
DataFrame.std() function to get the standard deviation of the data values.
0 2.738613 dtype: float64
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt data = pd.read_csv("C:/mtcars.csv") res_std = data['qsec'].std() print(res_std)
In the above example, we have used a dataset and calculated the standard deviation of the data column ‘qsec’ using the DataFrame.std() function.
Thus, in this article, we have understood the working of Python stdev() function along with NumPy and Pandas module.