mean imputation in python code example

Example 1: list mean python

# Python program to get average of a list

def Average(lst): 
	return sum(lst) / len(lst) 

# Driver Code 
lst = [15, 9, 55, 41, 35, 20, 62, 49] 
average = Average(lst) 

# Printing average of the list 
print("Average of the list =", round(average, 2)) 

# Output:
# Average of the list = 35.75

Example 2: how to calculate mean in python

import statistics

a = [1,2,3,4,5]

mean = statistics.mean(a) 
#Similar for other values such as variance, standard deviation

Example 3: replace missing values, encoded as np.nan, using the mean value of the columns

# Univariate feature imputation

import numpy as np
from sklearn.impute import SimpleImputer
imp = SimpleImputer(missing_values=np.nan, strategy='mean')
imp.fit([[1, 2], [np.nan, 3], [7, 6]])
# SimpleImputer()
X = [[np.nan, 2], [6, np.nan], [7, 6]]
print(imp.transform(X))
# [[4.          2.        ]
#  [6.          3.666...]
#  [7.          6.        ]]

# SimpleImputer class also supports categorical data

import pandas as pd
df = pd.DataFrame([["a", "x"],
                   [np.nan, "y"],
                   ["a", np.nan],
                   ["b", "y"]], dtype="category")

imp = SimpleImputer(strategy="most_frequent")
print(imp.fit_transform(df))
# [['a' 'x']
#  ['a' 'y']
#  ['a' 'y']
#  ['b' 'y']]