Find Standard Deviation in Python – List & pandas DataFrame (4 Examples)

This tutorial explains how to calculate the standard deviation in Python programming.

Example 1: Calculating the Standard Deviation of a List Object

my_lt = [10, 6, 2, 2, 15, 20, 3, 7, 4]      # Constructing a list in Python
print(my_lt)
# [10, 6, 2, 2, 15, 20, 3, 7, 4]
import numpy as np                          # Import NumPy library in Python
print(np.std(my_lt))                        # Computing the standard deviation of a list
# 5.9066817155564495

Example 2: Calculating the Standard Deviation of the Columns in a pandas DataFrame

import pandas as pd                         # Import pandas library in Python
my_df = pd.DataFrame({'A':range(10, 17),    # Constructing a pandas DataFrame
                      'B':[6, 1, 8, 5, 3, 8, 9],
                      'C':range(2, 9),
                      'GRP':['gr1', 'gr2', 'gr1', 'gr3', 'gr1', 'gr2', 'gr3']})
print(my_df)
#     A  B  C  GRP
# 0  10  6  2  gr1
# 1  11  1  3  gr2
# 2  12  8  4  gr1
# 3  13  5  5  gr3
# 4  14  3  6  gr1
# 5  15  8  7  gr2
# 6  16  9  8  gr3
print(my_df.std())                          # Computing the Standard Deviation of all columns
# A    2.160247
# B    2.927700
# C    2.160247
# dtype: float64

Example 3: Calculating the Standard Deviation of the Columns in a pandas DataFrame by Group

print(my_df.groupby('GRP').std())           # Computing the column standard deviations by group
#             A         B         C
# GRP                              
# gr1  2.000000  2.516611  2.000000
# gr2  2.828427  4.949747  2.828427
# gr3  2.121320  2.828427  2.121320

Example 4: Calculating the Standard Deviation of the Rows in a pandas DataFrame

print(my_df.std(axis = 1))                  # Computing the standard deviation of all rows
# 0    4.000000
# 1    5.291503
# 2    4.000000
# 3    4.618802
# 4    5.686241
# 5    4.358899
# 6    4.358899
# dtype: float64

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top