Remplacer les valeurs manquantes
Remplacez NaN par une constante, la moyenne de la colonne, un remplissage vers l’avant ou vers l’arrière avec fillna() et son paramètre method.
Remplacer les valeurs manquantes est une leçon Pandas & NumPy Academy gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Pandas & NumPy Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Pandas & NumPy Academy comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Introduction to fillna()
Imputation means replacing missing values with a reasonable substitute rather than dropping the row. Pandas fillna() is the primary tool for this: it replaces every NaN in a Series or DataFrame with a value you specify. Unlike dropping, imputation preserves all rows, which is especially important when data is scarce or when the missing-data pattern is informative.
The simplest form passes a scalar: df['col'].fillna(0).
import pandas as pd
import numpy as np
df = pd.DataFrame({
'product': ['A', 'B', 'C', 'D'],
'price': [10.0, np.nan, 30.0, np.nan]
})
# Fill all NaN in 'price' with 0
filled = df['price'].fillna(0)
print(filled)
# 0 10.0
# 1 0.0
# 2 30.0
# 3 0.0Filling with a Column Mean or Median
Filling with the column mean (for symmetric distributions) or median (for skewed distributions) is one of the most common imputation strategies. These statistics represent the central tendency of the data, so they minimise the distortion of the column's distribution. Always compute the statistic on the training split to avoid data leakage.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'salary': [50000, np.nan, 70000, 80000, np.nan, 60000]
})
mean_salary = df['salary'].mean()
median_salary = df['salary'].median()
df['salary_mean_filled'] = df['salary'].fillna(mean_salary)
df['salary_median_filled'] = df['salary'].fillna(median_salary)
print(df)
# salary salary_mean_filled salary_median_filled
# 0 50000.0 50000.0 50000.0
# 1 NaN 65000.0 65000.0
# 2 70000.0 70000.0 70000.0Filling Categoricals with Mode
For categorical columns, filling with the mean or median doesn't make sense. Instead, use the mode — the most frequently occurring value. Series.mode()[0] returns the most common value (the [0] handles the case where there are multiple modes).
import pandas as pd
import numpy as np
df = pd.DataFrame({
'status': ['active', 'inactive', None, 'active', None, 'active']
})
most_common = df['status'].mode()[0]
print('Mode:', most_common) # active
df['status'] = df['status'].fillna(most_common)
print(df['status'].tolist())
# ['active', 'inactive', 'active', 'active', 'active', 'active']Forward Fill with ffill()
Forward fill (also called last-observation-carried-forward, LOCF) propagates the last valid (non-NaN) value forward to fill subsequent NaN positions. It is ideal for time series data where a measurement stays constant until updated — for example, device status, price levels, or sensor readings that only change at specific events.
import pandas as pd
import numpy as np
price = pd.Series(
[100, np.nan, np.nan, 105, np.nan, 110],
index=pd.date_range('2024-01', periods=6, freq='ME')
)
filled = price.ffill()
print(filled)
# 2024-01-31 100.0
# 2024-02-29 100.0
# 2024-03-31 100.0
# 2024-04-30 105.0
# 2024-05-31 105.0
# 2024-06-30 110.0Backward Fill with bfill()
Backward fill (next-observation-carried-backward, NOCB) propagates the next valid value backward to fill preceding NaN positions. This is useful when you know future data fills in missing past values — for example, if you receive end-of-month data and need to back-fill days in that month before the report arrives.
import pandas as pd
import numpy as np
df = pd.DataFrame({'value': [np.nan, np.nan, 3, np.nan, 5]})
print(df['value'].bfill())
# 0 3.0
# 1 3.0
# 2 3.0
# 3 5.0
# 4 5.0
# dtype: float64limit Parameter for Forward and Backward Fill
Both ffill() and bfill() accept a limit parameter that restricts how many consecutive NaN values are filled. This is important when you want to carry a value forward only for a short gap — long gaps should remain NaN to signal that the data is genuinely missing, not just delayed.
import pandas as pd
import numpy as np
s = pd.Series([1.0, np.nan, np.nan, np.nan, 5.0])
# Fill only the first NaN gap, leave the rest
print(s.ffill(limit=1))
# 0 1.0
# 1 1.0 <- filled
# 2 NaN <- still NaN (limit reached)
# 3 NaN
# 4 5.0Filling Different Columns Differently
In a real DataFrame, different columns may need different fill strategies. Pass a dictionary to fillna() where keys are column names and values are the fill values. This applies column-specific imputation in a single call, which is cleaner than chaining multiple individual fillna calls.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'age': [25, np.nan, 30],
'income': [50000, np.nan, 70000],
'country': ['USA', np.nan, 'UK']
})
fill_values = {
'age': df['age'].median(),
'income': df['income'].mean(),
'country': 'Unknown'
}
filled = df.fillna(fill_values)
print(filled)
# age income country
# 0 25.0 50000.0 USA
# 1 27.5 60000.0 Unknown
# 2 30.0 70000.0 UKGroup-Aware Imputation
A more sophisticated strategy is to fill NaN values with the group mean or median rather than the overall column mean. For example, fill a missing salary with the median salary for that job category. This preserves subgroup structure and produces more realistic imputations than a global statistic.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'dept': ['Eng', 'Eng', 'HR', 'HR', 'Eng'],
'salary': [90000, np.nan, 50000, np.nan, 110000]
})
# Fill salary NaN with the median salary for each department
df['salary'] = df.groupby('dept')['salary'].transform(
lambda x: x.fillna(x.median())
)
print(df)
# dept salary
# 0 Eng 90000.0
# 1 Eng 100000.0 <- group median (90k+110k)/2
# 2 HR 50000.0
# 3 HR 50000.0
# 4 Eng 110000.0Filling with a Constant Sentinel Value
Sometimes the right imputation is a sentinel value that signals 'unknown' rather than a real measurement. For example, -1 for unknown age, 'N/A' for unknown category, or False for an unknown boolean flag. Sentinel values are valid when downstream code explicitly checks for them and treats them differently from real data.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'user_id': [1, 2, 3],
'referral_source': ['email', np.nan, 'ad'],
'trial_days': [14, np.nan, 7]
})
df['referral_source'] = df['referral_source'].fillna('unknown')
df['trial_days'] = df['trial_days'].fillna(-1).astype(int)
print(df)
# user_id referral_source trial_days
# 0 1 email 14
# 1 2 unknown -1
# 2 3 ad 7Chaining fillna() in a Pipeline
Like all Pandas methods, fillna() returns a new DataFrame and integrates cleanly into a method chain. Calling .fillna() after .dropna() applies a two-step strategy: drop rows missing critical columns, then fill remaining optional NaN values with sensible defaults — all in one readable pipeline.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'user_id': [1, None, 3, 4],
'score': [88, 95, np.nan, 76],
'label': ['A', 'B', None, 'D']
})
cleaned = (
df
.dropna(subset=['user_id'])
.fillna({'score': df['score'].mean(), 'label': 'Unknown'})
)
print(cleaned)
# user_id score label
# 0 1.0 88.0 A
# 2 3.0 86.3 Unknown
# 3 4.0 76.0 DVerifying No NaN Remains
After imputation, always verify that no NaN values remain in the columns you targeted. Call df.isna().sum() or assert that the count is zero. An unexpected non-zero count means your fillna was missing a case — perhaps a column had a dtype that prevented the fill, or you forgot a column in your dict.
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [1.0, np.nan, 3.0], 'b': [np.nan, 2.0, 3.0]})
filled = df.fillna(0)
# Verify
assert filled.isna().sum().sum() == 0, 'Some NaN remain!'
print('All NaN filled successfully')
print(filled.isna().sum())
# a 0
# b 0
# dtype: int64Quick Check
Test your understanding of filling missing values in Pandas.
Lesson Recap
In this lesson you learned: fillna(scalar) replaces all NaN with a constant, fillna(mean/median) imputes with column statistics, and ffill()/bfill() propagate adjacent values for time series. Pass a dictionary to fillna() for column-specific strategies, and use groupby().transform() for group-aware imputation. Next up we cover interpolation and when to choose advanced imputation techniques.
Questions Fréquemment Posées
La leçon « Remplacer les valeurs manquantes » est-elle gratuite ?
Oui — le texte complet de « Remplacer les valeurs manquantes » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Pandas & NumPy Academy, passe à CoddyKit PRO. Le cours Pandas & NumPy Academy comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Remplacer les valeurs manquantes » ?
Remplacez NaN par une constante, la moyenne de la colonne, un remplissage vers l’avant ou vers l’arrière avec fillna() et son paramètre method. Tu pratiques Pandas & NumPy Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Pandas & NumPy Academy ?
Aucune expérience préalable n'est requise. Pandas & NumPy Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « Remplacer les valeurs manquantes » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Pandas & NumPy Academy ?
Oui. Chaque leçon Pandas & NumPy Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Détecter les valeurs manquantes
- Supprimer les valeurs manquantes
- Remplacer les valeurs manquantes
- Interpolation et imputation avancée