บทนำ
Mode (ฐานนิยม) คือค่าที่เกิดขึ้นบ่อยที่สุด ใช้ fillna() ร่วมกับ mode() เติมค่าขาดหายในคอลัมน์ categorical หรือ discrete
ตัวอย่างโค้ด
import pandas as pd
import numpy as np
df = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],
"Units": [100, 150, np.NaN, 80, np.NaN, np.NaN]
})
print("DataFrame ต้นทาง:")
print(df)
# Mode ของคอลัมน์ Units
mode_val = df['Units'].mode()
print(f"\nMode(s): {mode_val.tolist()}") # อาจมีหลายค่า
# ใช้ mode แรก [0]
df['Units'].fillna(df['Units'].mode()[0], inplace=True)
print("\nDataFrame หลังเติม NaN ด้วย Mode:")
print(df)
ผลลัพธ์
DataFrame ต้นทาง:
Car Units
0 BMW 100.0
1 Lexus 150.0
2 Lexus NaN
3 Mustang 80.0
4 Bentley NaN
5 Mustang NaN
Mode(s): [80.0]
DataFrame หลังเติม NaN ด้วย Mode:
Car Units
0 BMW 100.0
1 Lexus 150.0
2 Lexus 80.0
3 Mustang 80.0
4 Bentley 80.0
5 Mustang 80.0
คำอธิบาย
- ค่า Units ที่มี: 100, 150, 80 (NaN ไม่นับ)
- แต่ละค่ามี 1 ครั้ง → multimodal (หลาย mode)
- Pandas
mode()คืน Series ของ mode ทั้งหมด → ใช้[0]เอาตัวแรก - ในตัวอย่าง 80 เป็น mode แรกที่พบ (index 3)
ข้อควรระวัง: Multimodal Data
# ข้อมูลที่มีหลาย mode
s = pd.Series([1, 1, 2, 2, 3])
print(s.mode()) # 0 1, 1 2 (สอง mode)
# การใช้ [0] อาจ arbitrary
# แนะนำ: ตรวจสอบจำนวน mode ก่อน
modes = s.mode()
if len(modes) > 1:
print(f"พบ {len(modes)} modes: {modes.tolist()}")
# อาจเลือก median หรือ mean แทน
เปรียบเทียบ Imputation Methods
| Method | Code | เหมาะกับ |
|---|---|---|
| Mean | fillna(df[col].mean()) | Numeric, normal dist |
| Median | fillna(df[col].median()) | Numeric, skewed/outliers |
| Mode | fillna(df[col].mode()[0]) | Categorical, discrete |
| Constant | fillna(value=0) | Known default |
| Forward fill | fillna(method='ffill') | Time series |
| Interpolate | interpolate() | Time series, numeric |
เติม NaN หลายคอลัมน์ด้วย Mode
# เฉพาะคอลัมน์ object/category
cat_cols = df.select_dtypes(include=['object', 'category']).columns
for col in cat_cols:
if df[col].isna().any():
mode_val = df[col].mode()
if len(mode_val) > 0:
df[col].fillna(mode_val[0], inplace=True)
สรุป
ใช้ df['col'].fillna(df['col'].mode()[0]) เติม NaN ด้วย mode สำหรับ categorical/discrete data ข้อควรระวัง: mode() อาจคืนหลายค่า (multimodal) ควรตรวจสอบหรือเลือกวิธีอื่น