0Pricing
Machine Learning Academy · บทเรียน

การจัดการค่าที่หายไป: ลบ เติมค่า และทำเครื่องหมาย

ผู้เรียนจะตรวจหาค่าว่าง ใช้การเติมค่าด้วยค่าเฉลี่ย ค่ามัธยฐาน หรือค่าที่พบบ่อยที่สุดด้วย SimpleImputer และตัดสินใจว่าเมื่อใดการลบแถวปลอดภัยกว่าการเติมค่า

การจัดการค่าที่หายไป: ลบ เติมค่า และทำเครื่องหมาย เป็นบทเรียน Machine Learning Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Machine Learning Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Missing Values Are Dangerous

Missing values — represented as NaN, None, or empty cells — are one of the most common data quality issues in real-world datasets. If left unhandled, they cause errors in scikit-learn estimators, which expect fully numeric matrices. Every ML pipeline must address missing values before training. There are three main strategies: drop rows/columns, impute (fill in estimated values), or flag the missingness as its own feature.

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'age': [25, np.nan, 35, np.nan, 50],
    'income': [40000, 55000, np.nan, 72000, 90000],
    'score': [85, 90, 78, np.nan, 95]
})

print(df.isnull().sum())  # Count nulls per column
print(df.isnull().mean())  # Fraction missing per column

Detecting Nulls with Pandas

Before deciding how to handle missing values, you need to quantify the problem. Pandas provides df.isnull() to create a boolean mask and df.isnull().sum() to count nulls per column. The df.info() method also shows non-null counts. Always inspect the fraction of missing values — if more than 50% of a column is missing, that column may need to be dropped entirely rather than imputed.

import pandas as pd
import numpy as np

df = pd.read_csv('housing.csv')

# Fraction missing per column (sorted)
missing_frac = df.isnull().mean().sort_values(ascending=False)
print(missing_frac[missing_frac > 0])

# Heat map of missing values
import seaborn as sns
import matplotlib.pyplot as plt
sns.heatmap(df.isnull(), cbar=False)
plt.show()

Dropping Rows and Columns

df.dropna() removes rows containing any null by default. Pass axis=1 to drop columns instead. The thresh parameter lets you keep rows that have at least N non-null values. Dropping is safe when missingness is completely random (MCAR) and the fraction is tiny — less than 1-5% of rows. However, dropping too aggressively causes information loss and can introduce bias if the data is not missing at random.

# Drop rows with ANY null
df_no_null = df.dropna()

# Drop columns where MORE than 40% of values are missing
df_cleaned = df.dropna(axis=1, thresh=int(0.6 * len(df)))

# Drop rows only if specific columns are null
df_subset = df.dropna(subset=['age', 'income'])

print('Original shape:', df.shape)
print('After drop:', df_no_null.shape)

Mean and Median Imputation

Imputation fills missing values with estimated substitutes. Mean imputation replaces nulls with the column mean, which works well for symmetric, normally distributed data. Median imputation is more robust to outliers and is preferred for skewed distributions. Both are simple and fast but reduce variance artificially since all imputed values are identical. Use SimpleImputer from scikit-learn for pipeline-compatible imputation.

from sklearn.impute import SimpleImputer
import numpy as np

X = np.array([[1, 2], [np.nan, 3], [7, 6], [np.nan, np.nan]])

# Mean imputation
imp_mean = SimpleImputer(strategy='mean')
X_mean = imp_mean.fit_transform(X)
print('Mean imputed:\n', X_mean)

# Median imputation (more robust)
imp_median = SimpleImputer(strategy='median')
X_median = imp_median.fit_transform(X)
print('Median imputed:\n', X_median)

Most-Frequent Imputation for Categoricals

For categorical columns, using mean or median makes no sense. Instead, use strategy='most_frequent' in SimpleImputer, which fills missing values with the mode (most common category). This preserves the distribution shape better than random assignment. Always fit the imputer only on training data and use the fitted imputer to transform both train and test sets — this prevents data leakage from the test set influencing the imputed values.

from sklearn.impute import SimpleImputer
import numpy as np

X_cat = np.array([
    ['cat'],
    ['dog'],
    [np.nan],
    ['cat'],
    [np.nan]
])

imp = SimpleImputer(strategy='most_frequent')
X_imputed = imp.fit_transform(X_cat)
print(X_imputed.flatten())
# Output: ['cat' 'dog' 'cat' 'cat' 'cat']

Constant and Custom Imputation

Sometimes the best imputed value is a domain-specific constant, not a statistic. For example, missing number of previous purchases likely means zero. Use strategy='constant' with fill_value=0 in SimpleImputer. For more complex logic — like filling missing city with 'Unknown' — pass a string constant. Constant imputation is interpretable and safe when absence genuinely implies a specific value rather than data collection failure.

from sklearn.impute import SimpleImputer
import numpy as np

# Numeric: fill 0 (e.g., previous purchases)
imp_zero = SimpleImputer(strategy='constant', fill_value=0)

# Categorical: fill with 'Unknown'
imp_unknown = SimpleImputer(strategy='constant', fill_value='Unknown')

X_num = np.array([[5], [np.nan], [3], [np.nan]])
X_cat = np.array([['Paris'], [None], ['Tokyo'], [None]])

print(imp_zero.fit_transform(X_num).flatten())
print(imp_unknown.fit_transform(X_cat).flatten())

KNN and Iterative Imputation

More sophisticated imputers model the relationship between features to produce better estimates. KNNImputer fills a missing value by looking at the k nearest complete rows and averaging their values — preserving local data structure. IterativeImputer (experimental) fits a separate regression model for each feature with nulls, using all other features as predictors. Both are more accurate than mean imputation but are slower and can overfit on small datasets.

from sklearn.impute import KNNImputer
import numpy as np

X = np.array([
    [1, 2, np.nan],
    [3, 4, 3],
    [np.nan, 6, 5],
    [8, 8, 7]
])

imp = KNNImputer(n_neighbors=2)
X_filled = imp.fit_transform(X)
print('KNN imputed:\n', X_filled)

Missing Indicator: Flagging Missingness

Sometimes the fact that a value is missing is itself informative. For instance, a missing salary field might indicate unemployment. Adding a binary indicator column that marks whether each value was originally null allows the model to learn from the missingness pattern. MissingIndicator in scikit-learn creates these flag columns. Use it together with imputation in a FeatureUnion or ColumnTransformer so the model sees both the imputed value and the flag.

from sklearn.impute import SimpleImputer, MissingIndicator
from sklearn.pipeline import FeatureUnion
import numpy as np

X = np.array([[1, 2], [np.nan, 3], [7, 6], [np.nan, np.nan]])

indicator = MissingIndicator()
flags = indicator.fit_transform(X)
print('Missing flags:\n', flags)
# Adds True/False columns marking original NaN positions

Train-Test Imputation Without Leakage

A critical rule: always fit the imputer on training data only, then use the fitted imputer to transform both train and test sets. Fitting on the full dataset leaks test statistics into training, giving optimistic evaluation results. This applies to every statistic computed during preprocessing — mean, median, mode, or nearest-neighbor distances. Use scikit-learn Pipeline to enforce this automatically: the pipeline fits preprocessing steps only on the training fold during cross-validation.

from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
import numpy as np

X = np.array([[1, 2], [np.nan, 3], [7, 6], [5, np.nan], [9, 1]])
y = np.array([0, 1, 0, 1, 0])

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

imp = SimpleImputer(strategy='mean')
imp.fit(X_train)        # Fit ONLY on training data
X_train_imp = imp.transform(X_train)
X_test_imp = imp.transform(X_test)  # Apply same stats to test

When to Drop vs Impute vs Flag

Choosing the right strategy depends on three factors: (1) fraction missing — below 5% dropping rows is acceptable; above 50% consider dropping the column; (2) mechanism — MCAR (completely random) favours dropping; MAR (random given other features) favours imputation; MNAR (not at random) favours flagging; (3) downstream model — tree-based models handle missing data natively (set allow_nan=True in XGBoost/LightGBM), so imputation may be optional. Always cross-validate to confirm your strategy improves model performance.

# Decision guide in code form
def imputation_strategy(fraction_missing, is_informative):
    if fraction_missing > 0.6:
        return 'drop column'
    elif fraction_missing < 0.02:
        return 'drop rows'
    elif is_informative:
        return 'impute + add flag column'
    else:
        return 'impute (mean/median/mode)'

print(imputation_strategy(0.7, False))   # drop column
print(imputation_strategy(0.01, False))  # drop rows
print(imputation_strategy(0.2, True))    # impute + flag

Full Imputation Pipeline Example

Here is a complete example combining imputation into a scikit-learn pipeline. ColumnTransformer applies SimpleImputer with strategy='median' to numeric columns and strategy='most_frequent' to categorical columns simultaneously. The result flows into a classifier, and the whole pipeline is safely cross-validated so imputation statistics never leak between folds. This pattern is the production-ready approach to missing data handling in any real ML project.

from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

num_features = ['age', 'income']
cat_features = ['city']

preprocessor = ColumnTransformer([
    ('num', SimpleImputer(strategy='median'), num_features),
    ('cat', SimpleImputer(strategy='most_frequent'), cat_features)
])

pipeline = Pipeline([
    ('prep', preprocessor),
    ('clf', RandomForestClassifier(random_state=42))
])

scores = cross_val_score(pipeline, X, y, cv=5)
print('CV accuracy:', scores.mean())

Quick Check

Test your understanding of Machine Learning with Python concepts from this lesson.

Lesson Recap

In this lesson you learned: how to detect missing values using isnull().sum() and info(), three main strategies — drop, impute, and flag — and when each is appropriate, and how to use SimpleImputer, KNNImputer, and MissingIndicator within a pipeline to prevent leakage. Next up we explore feature scaling with StandardScaler and MinMaxScaler.

คำถามที่พบบ่อย

บทเรียน “การจัดการค่าที่หายไป: ลบ เติมค่า และทำเครื่องหมาย” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจัดการค่าที่หายไป: ลบ เติมค่า และทำเครื่องหมาย” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Machine Learning Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจัดการค่าที่หายไป: ลบ เติมค่า และทำเครื่องหมาย”

ผู้เรียนจะตรวจหาค่าว่าง ใช้การเติมค่าด้วยค่าเฉลี่ย ค่ามัธยฐาน หรือค่าที่พบบ่อยที่สุดด้วย SimpleImputer และตัดสินใจว่าเมื่อใดการลบแถวปลอดภัยกว่าการเติมค่า คุณปฏิบัติ Machine Learning Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Machine Learning Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Machine Learning Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การจัดการค่าที่หายไป: ลบ เติมค่า และทำเครื่องหมาย” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Machine Learning Academy นี้ได้ไหม

ได้ บทเรียน Machine Learning Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การจัดการค่าที่หายไป: ลบ เติมค่า และทำเครื่องหมาย
  2. การปรับสเกลคุณลักษณะ: StandardScaler และ MinMaxScaler
  3. การเข้ารหัสตัวแปรเชิงกลุ่ม: OrdinalEncoder และ OneHotEncoder
  4. การรวมขั้นตอนด้วย ColumnTransformer
← กลับไปที่ Machine Learning Academy