Last updated

Handling Missing Data

Definition: Real data often has gaps. Pandas marks missing values as NaN (Not a Number). You can either drop those rows or fill the gaps with a value.

Example 1 — spot the missing values

import pandas as pd
import numpy as np
df = pd.DataFrame({
  "name":  ["A", "B", "C"],
  "score": [90, np.nan, 75]
})
print(df)
print(df.isnull().sum())   # count missing per column

Example 2 — drop rows with gaps

import pandas as pd
import numpy as np
df = pd.DataFrame({"name": ["A","B","C"], "score": [90, np.nan, 75]})
print(df.dropna())   # removes row B

Example 3 — fill the gaps

import pandas as pd
import numpy as np
df = pd.DataFrame({"score": [90, np.nan, 75]})
print(df.fillna(0))                       # fill with 0
print(df.fillna(df["score"].mean()))      # fill with the average

💡 Tip: dropping is simplest, but filling with the mean (or median) often keeps more useful data. Choose based on your situation.

Try it Yourself
Output

          
Ad · responsive