Fill-Na-With-Average
Sat 17 May 2025
title: "Fill NA with Average" author: "Rj" date: 2019-04-22 description: "-" type: technical_note draft: false
import numpy as np
import pandas as pd
df = pd.read_csv('abc2.csv')
df
| student | language | science | maths | history | |
|---|---|---|---|---|---|
| 0 | kumar | 90 | 56.0 | 34.0 | 34 |
| 1 | kevin | 10 | NaN | 32.0 | 67 |
| 2 | sammy | 90 | 23.0 | 12.0 | 32 |
| 3 | janice | 20 | NaN | 90.0 | 45 |
| 4 | peter | 30 | 56.0 | 45.0 | 65 |
| 5 | prem | 90 | 45.0 | NaN | 34 |
| 6 | carrol | 50 | 90.0 | 45.0 | 23 |
# We are going to fill mean value on the NAs.
df.fillna(df.mean(), inplace=True)
df
| student | language | science | maths | history | |
|---|---|---|---|---|---|
| 0 | kumar | 90 | 56.0 | 34.0 | 34 |
| 1 | kevin | 10 | 54.0 | 32.0 | 67 |
| 2 | sammy | 90 | 23.0 | 12.0 | 32 |
| 3 | janice | 20 | 54.0 | 90.0 | 45 |
| 4 | peter | 30 | 56.0 | 45.0 | 65 |
| 5 | prem | 90 | 45.0 | 43.0 | 34 |
| 6 | carrol | 50 | 90.0 | 45.0 | 23 |
Note
inplace=True param will change the current object (in this case our dataframe).
Score: 5
Category: data-wrangling