Write a Python program to find the mean absolute deviation of rows and columns in a dataframe

PythonPandasServer Side ProgrammingProgramming

Solution

Assume you have a dataframe and mean absolute deviation of rows and column is,

mad of columns:
Column1    0.938776
Column2    0.600000
dtype: float64

mad of rows:
0    0.500
1    0.900
2    0.650
3    0.900
4    0.750
5    0.575
6    1.325
dtype: float64

To solve this, we will follow the steps given below −

  • Define a dataframe

  • Calculate mean absolute deviation of row as,

df.mad()
  • Calculate mean absolute deviation of row as,

df.mad(axis=1)

Example

Let’s see the following code to get a better understanding −

import pandas as pd
data = {"Column1":[6, 5.3, 5.9, 7.8, 7.6, 7.45, 7.75],
         "Column2":[7, 7.1, 7.2, 6, 6.1, 6.3, 5.1]}
df = pd.DataFrame(data)
print("DataFrame is:\n",df)
print("mad of columns:\n",df.mad())
print("mad of rows:\n",df.mad(axis=1))

Output

DataFrame is:
   Column1 Column2
0    6.00    7.0
1    5.30    7.1
2    5.90    7.2
3    7.80    6.0
4    7.60    6.1
5    7.45    6.3
6    7.75    5.1

mad of columns:
Column1    0.938776
Column2    0.600000
dtype: float64

mad of rows:
0    0.500
1    0.900
2    0.650
3    0.900
4    0.750
5    0.575
6    1.325
dtype: float64
raja
Published on 11-Feb-2021 11:30:34
Advertisements