Data Science หรือวิทยาศาสตร์ข้อมูล เป็นสาขาที่เติบโตเร็วที่สุดในอุตสาหกรรม Tech ปี 2026 ข้อมูลมหาศาลถูกสร้างขึ้นทุกวินาที และองค์กรที่สามารถวิเคราะห์ข้อมูลเหล่านี้ได้อย่างมีประสิทธิภาพจะได้เปรียบคู่แข่งอย่างมาก Python กลายเป็นภาษาอันดับหนึ่งสำหรับ Data Science เพราะมี Library ที่ทรงพลัง ชุมชนขนาดใหญ่ และเรียนรู้ง่ายแม้สำหรับผู้เริ่มต้น
บทความนี้จะพาคุณเรียนรู้ Python สำหรับ Data Science ตั้งแต่พื้นฐาน NumPy สำหรับการคำนวณเชิงตัวเลข Pandas สำหรับจัดการข้อมูลแบบตาราง Matplotlib และ Seaborn สำหรับสร้าง Visualization ไปจนถึง Workflow การทำ Exploratory Data Analysis (EDA) ที่ใช้ในงานจริง พร้อมตัวอย่างโค้ดที่รันได้ทันที
ทำไมต้อง Python สำหรับ Data Science?
ในบรรดาภาษาโปรแกรมทั้งหมดที่ใช้ในงาน Data Science มีเหตุผลหลายประการที่ทำให้ Python เป็นตัวเลือกอันดับหนึ่ง ประการแรก Python มี Syntax ที่อ่านง่ายเหมือนภาษาอังกฤษ ทำให้นักวิทยาศาสตร์ข้อมูลที่อาจไม่ได้มีพื้นฐานโปรแกรมมิ่งมากนักสามารถเรียนรู้ได้อย่างรวดเร็ว ประการที่สอง Python มี Ecosystem ของ Library ที่ครบครัน ตั้งแต่ NumPy สำหรับการคำนวณเชิงตัวเลข Pandas สำหรับจัดการข้อมูล Matplotlib และ Seaborn สำหรับ Visualization ไปจนถึง scikit-learn สำหรับ Machine Learning และ TensorFlow/PyTorch สำหรับ Deep Learning
ประการที่สาม Jupyter Notebook ทำให้การทำงานกับข้อมูลเป็นแบบ Interactive สามารถเขียนโค้ด ดูผลลัพธ์ และเขียนบันทึกในที่เดียว ประการที่สี่ ชุมชน Python มีขนาดใหญ่มาก มีคำตอบสำหรับปัญหาเกือบทุกอย่างบน Stack Overflow และ GitHub และประการสุดท้าย Python เป็นภาษาอเนกประสงค์ที่ใช้ได้ตั้งแต่ Web Development ไปจนถึง Automation ทำให้เป็น Skill ที่มีคุณค่าสูงในตลาดงาน
การติดตั้ง Python สำหรับ Data Science
# วิธีที่แนะนำ: ติดตั้ง Anaconda (รวม Python + Library ทั้งหมด)
# ดาวน์โหลดจาก https://www.anaconda.com/download
# หรือติดตั้ง Python แล้วใช้ pip
pip install numpy pandas matplotlib seaborn jupyter scikit-learn
# สร้าง Virtual Environment (แนะนำ)
python -m venv datascience-env
source datascience-env/bin/activate # Linux/Mac
datascience-env\Scripts\activate # Windows
# เริ่ม Jupyter Notebook
jupyter notebook
# หรือ JupyterLab (UI ที่ดีกว่า)
pip install jupyterlab
jupyter lab
NumPy — รากฐานของ Data Science
NumPy (Numerical Python) เป็น Library พื้นฐานที่สุดสำหรับการคำนวณเชิงตัวเลขใน Python ทุก Library ด้าน Data Science อื่นๆ ล้วนสร้างอยู่บน NumPy ข้อได้เปรียบหลักของ NumPy คือ ndarray ซึ่งเป็น Array ที่เก็บข้อมูลชนิดเดียวกันอย่างมีประสิทธิภาพ เร็วกว่า Python List หลายสิบเท่าเพราะใช้ C ในการคำนวณเบื้องหลัง
การสร้าง NumPy Array
import numpy as np
# สร้าง Array จาก List
arr1d = np.array([1, 2, 3, 4, 5])
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr1d.shape) # (5,)
print(arr2d.shape) # (3, 3)
print(arr2d.dtype) # int64
print(arr2d.ndim) # 2
# สร้าง Array แบบพิเศษ
zeros = np.zeros((3, 4)) # Array ศูนย์ทั้งหมด
ones = np.ones((2, 3)) # Array หนึ่งทั้งหมด
full = np.full((3, 3), 7) # Array เต็มด้วยค่า 7
eye = np.eye(4) # Identity Matrix 4x4
arange = np.arange(0, 20, 2) # [0, 2, 4, 6, ..., 18]
linspace = np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1.0]
random_arr = np.random.randn(3, 3) # Random Normal Distribution
Indexing และ Slicing
arr = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# Basic Indexing
print(arr[0, 0]) # 1
print(arr[2, 3]) # 12
print(arr[1]) # [5, 6, 7, 8] — แถวที่ 1
# Slicing
print(arr[0:2, 1:3]) # [[2, 3], [6, 7]]
print(arr[:, 0]) # [1, 5, 9] — คอลัมน์แรก
print(arr[-1, :]) # [9, 10, 11, 12] — แถวสุดท้าย
# Boolean Indexing (สำคัญมาก!)
print(arr[arr > 5]) # [6, 7, 8, 9, 10, 11, 12]
mask = (arr > 3) & (arr < 10)
print(arr[mask]) # [4, 5, 6, 7, 8, 9]
# Fancy Indexing
rows = [0, 2]
cols = [1, 3]
print(arr[rows, cols]) # [2, 12]
Broadcasting และ Vectorization
Broadcasting เป็นคุณสมบัติที่ทรงพลังที่สุดอย่างหนึ่งของ NumPy ช่วยให้สามารถคำนวณระหว่าง Array ที่มีขนาดต่างกันได้โดยอัตโนมัติ ส่วน Vectorization คือการทำ Operation กับ Array ทั้งหมดในครั้งเดียวโดยไม่ต้องใช้ Loop ซึ่งเร็วกว่าการใช้ for loop อย่างมาก
# Vectorization — ไม่ต้องใช้ Loop
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
print(a + b) # [11, 22, 33, 44]
print(a * b) # [10, 40, 90, 160]
print(a ** 2) # [1, 4, 9, 16]
print(np.sqrt(a)) # [1., 1.414, 1.732, 2.]
# Broadcasting — คำนวณกับ Scalar
print(a * 10) # [10, 20, 30, 40]
print(a + 100) # [101, 102, 103, 104]
# Broadcasting — Array ต่างขนาด
matrix = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3)
vector = np.array([10, 20, 30]) # shape (3,)
print(matrix + vector) # [[11, 22, 33], [14, 25, 36]]
# เปรียบเทียบความเร็ว: Loop vs Vectorization
import time
size = 1_000_000
py_list = list(range(size))
np_arr = np.arange(size)
# Python Loop — ช้า
start = time.time()
result = [x * 2 for x in py_list]
print(f"Python Loop: {time.time() - start:.4f}s")
# NumPy Vectorized — เร็ว
start = time.time()
result = np_arr * 2
print(f"NumPy Vectorized: {time.time() - start:.4f}s")
# NumPy เร็วกว่า 50-100 เท่า!
ฟังก์ชันสำคัญของ NumPy
data = np.array([23, 45, 12, 67, 34, 89, 56, 78, 11, 90])
# สถิติพื้นฐาน
print(np.mean(data)) # ค่าเฉลี่ย: 50.5
print(np.median(data)) # ค่ามัธยฐาน: 50.5
print(np.std(data)) # ส่วนเบี่ยงเบนมาตรฐาน
print(np.var(data)) # ความแปรปรวน
print(np.min(data)) # ค่าต่ำสุด: 11
print(np.max(data)) # ค่าสูงสุด: 90
print(np.sum(data)) # ผลรวม: 505
print(np.percentile(data, 75)) # Percentile ที่ 75
# การจัดเรียง
print(np.sort(data)) # เรียงน้อย -> มาก
print(np.argsort(data)) # Index ของการเรียง
# Linear Algebra
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(np.dot(A, B)) # Matrix multiplication
print(A @ B) # เหมือนกัน (Python 3.5+)
print(np.linalg.inv(A)) # Inverse matrix
print(np.linalg.det(A)) # Determinant
eigenvalues, eigenvectors = np.linalg.eig(A) # Eigenvalues
# Reshape
arr = np.arange(12)
print(arr.reshape(3, 4)) # เปลี่ยนเป็น 3x4
print(arr.reshape(2, -1)) # -1 = คำนวณอัตโนมัติ -> 2x6
Pandas — พลังแห่งการจัดการข้อมูล
Pandas เป็น Library ที่สำคัญที่สุดสำหรับการจัดการข้อมูลแบบตาราง (Tabular Data) ใน Python โครงสร้างข้อมูลหลักของ Pandas คือ Series (1 มิติ เหมือนคอลัมน์เดียว) และ DataFrame (2 มิติ เหมือนตาราง Excel หรือ SQL Table) Pandas ทำให้การอ่าน ทำความสะอาด วิเคราะห์ และแปลงข้อมูลเป็นเรื่องง่ายและรวดเร็ว
Series และ DataFrame พื้นฐาน
import pandas as pd
# Series — ข้อมูล 1 มิติ
prices = pd.Series([100, 200, 150, 300], index=['A', 'B', 'C', 'D'])
print(prices['B']) # 200
print(prices[prices > 150]) # B: 200, D: 300
# DataFrame — ข้อมูล 2 มิติ (ตาราง)
data = {
'name': ['สมชาย', 'สมหญิง', 'สมศรี', 'สมศักดิ์', 'สมใจ'],
'age': [25, 30, 28, 35, 22],
'salary': [35000, 55000, 42000, 70000, 28000],
'department': ['IT', 'Marketing', 'IT', 'Management', 'IT']
}
df = pd.DataFrame(data)
print(df)
print(df.info()) # ข้อมูลทั่วไป
print(df.describe()) # สถิติพื้นฐาน
print(df.shape) # (5, 4)
print(df.columns) # Index(['name', 'age', 'salary', 'department'])
print(df.dtypes) # ชนิดข้อมูลแต่ละคอลัมน์
การอ่านข้อมูลจากไฟล์
# CSV — ใช้บ่อยที่สุด
df = pd.read_csv('sales_data.csv')
df = pd.read_csv('data.csv', encoding='utf-8-sig') # ภาษาไทย
df = pd.read_csv('data.csv', sep=';') # คั่นด้วย ;
# Excel
df = pd.read_excel('report.xlsx', sheet_name='Sheet1')
# JSON
df = pd.read_json('api_response.json')
# SQL Database
import sqlite3
conn = sqlite3.connect('database.db')
df = pd.read_sql('SELECT * FROM users', conn)
# จาก URL
df = pd.read_csv('https://example.com/data.csv')
# บันทึกข้อมูล
df.to_csv('output.csv', index=False, encoding='utf-8-sig')
df.to_excel('output.xlsx', index=False)
df.to_json('output.json', orient='records', force_ascii=False)
การเลือกและกรองข้อมูล
# เลือกคอลัมน์
print(df['name']) # Series เดียว
print(df[['name', 'salary']]) # หลายคอลัมน์
# เลือกแถว
print(df.iloc[0]) # แถวแรก (by position)
print(df.iloc[0:3]) # แถว 0-2
print(df.loc[0]) # แถวแรก (by label)
# กรองข้อมูล (Filtering)
it_dept = df[df['department'] == 'IT']
high_salary = df[df['salary'] > 40000]
# หลายเงื่อนไข
senior_it = df[(df['department'] == 'IT') & (df['age'] > 25)]
it_or_mkt = df[df['department'].isin(['IT', 'Marketing'])]
# Query method (อ่านง่ายกว่า)
result = df.query('salary > 40000 and department == "IT"')
# เลือกคอลัมน์ + กรองแถว
print(df.loc[df['age'] > 25, ['name', 'salary']])
การจัดการข้อมูลขั้นสูง
# เพิ่มคอลัมน์ใหม่
df['bonus'] = df['salary'] * 0.1
df['tax'] = df['salary'].apply(lambda x: x * 0.05 if x > 40000 else 0)
df['age_group'] = pd.cut(df['age'], bins=[20, 25, 30, 40], labels=['Junior', 'Mid', 'Senior'])
# Sorting
df_sorted = df.sort_values('salary', ascending=False)
df_sorted = df.sort_values(['department', 'salary'], ascending=[True, False])
# Groupby — การรวมกลุ่มข้อมูล
dept_stats = df.groupby('department').agg({
'salary': ['mean', 'min', 'max', 'count'],
'age': 'mean'
})
print(dept_stats)
# GroupBy แบบง่าย
print(df.groupby('department')['salary'].mean())
# Pivot Table
pivot = pd.pivot_table(df, values='salary', index='department',
aggfunc=['mean', 'count', 'sum'])
print(pivot)
# Value Counts — นับจำนวน
print(df['department'].value_counts())
# String Methods
df['name_upper'] = df['name'].str.upper()
df['has_pattern'] = df['name'].str.contains('สม')
# Date Operations
df['date'] = pd.to_datetime(df.get('date', '2026-01-01'))
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day_name'] = df['date'].dt.day_name()
df.info() เป็นคำสั่งแรกเสมอเมื่อได้ข้อมูลใหม่ จะเห็น Data Type, จำนวน Non-null, และ Memory Usage ของทุกคอลัมน์
การ Merge และ Join ข้อมูล
# สร้างข้อมูลตัวอย่าง
employees = pd.DataFrame({
'emp_id': [1, 2, 3, 4],
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'dept_id': [101, 102, 101, 103]
})
departments = pd.DataFrame({
'dept_id': [101, 102, 103, 104],
'dept_name': ['Engineering', 'Marketing', 'Sales', 'HR']
})
# Inner Join (default) — เฉพาะที่ตรงกัน
merged = pd.merge(employees, departments, on='dept_id')
# Left Join — เอาข้อมูลจากตารางซ้ายทั้งหมด
merged = pd.merge(employees, departments, on='dept_id', how='left')
# Outer Join — เอาทั้งหมด
merged = pd.merge(employees, departments, on='dept_id', how='outer')
# Concatenation — ต่อ DataFrame
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
combined = pd.concat([df1, df2], ignore_index=True)
การจัดการ Missing Data
ข้อมูลจริงมักจะไม่สมบูรณ์ การจัดการ Missing Data (ค่าว่าง/NaN) เป็นทักษะสำคัญมากใน Data Science ถ้าจัดการไม่ดี ผลการวิเคราะห์จะผิดพลาดได้ Pandas มีเครื่องมือที่ครบครันสำหรับจัดการกับ Missing Data ทุกรูปแบบ ไม่ว่าจะเป็นการตรวจสอบ ลบ หรือเติมค่าแทน
# สร้างข้อมูลที่มี Missing Values
data = {
'name': ['A', 'B', 'C', 'D', 'E'],
'age': [25, None, 30, None, 28],
'salary': [35000, 50000, None, 60000, None],
'city': ['BKK', 'CNX', None, 'BKK', 'CNX']
}
df = pd.DataFrame(data)
# ตรวจสอบ Missing Data
print(df.isnull().sum()) # จำนวน NaN ต่อคอลัมน์
print(df.isnull().sum() / len(df) * 100) # เปอร์เซ็นต์ NaN
# ลบแถวที่มี NaN
df_dropped = df.dropna() # ลบทุกแถวที่มี NaN
df_dropped = df.dropna(subset=['age']) # ลบเฉพาะที่ age เป็น NaN
# เติมค่าแทน NaN
df['age'] = df['age'].fillna(df['age'].mean()) # เติมด้วยค่าเฉลี่ย
df['salary'] = df['salary'].fillna(df['salary'].median()) # เติมด้วยค่ามัธยฐาน
df['city'] = df['city'].fillna('Unknown') # เติมด้วยค่าคงที่
# Forward/Backward Fill (เหมาะกับ Time Series)
df['value'] = df['salary'].ffill() # เติมด้วยค่าก่อนหน้า
df['value'] = df['salary'].bfill() # เติมด้วยค่าถัดไป
# Interpolation
df['salary_interp'] = df['salary'].interpolate(method='linear')
Data Cleaning — ทำความสะอาดข้อมูล
ในโลกจริง ข้อมูลที่ได้มามักจะสกปรก มีค่าผิดปกติ มีข้อมูลซ้ำ หรือ Format ไม่ตรง การทำความสะอาดข้อมูล (Data Cleaning) เป็นขั้นตอนที่ Data Scientist ใช้เวลามากที่สุด บางงานวิจัยบอกว่าถึง 80 เปอร์เซ็นต์ของเวลาทั้งหมดหมดไปกับการทำความสะอาดข้อมูล ถ้าข้อมูลสกปรก ผลการวิเคราะห์ก็ไม่มีความหมาย หรือที่เรียกว่า Garbage In, Garbage Out
# ลบข้อมูลซ้ำ (Duplicate)
print(df.duplicated().sum()) # นับจำนวนแถวซ้ำ
df = df.drop_duplicates() # ลบแถวซ้ำ
df = df.drop_duplicates(subset=['name', 'age']) # ดูเฉพาะบางคอลัมน์
# เปลี่ยนชนิดข้อมูล
df['age'] = df['age'].astype(int)
df['salary'] = pd.to_numeric(df['salary'], errors='coerce') # แปลงเป็นตัวเลข
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
# ตรวจจับ Outliers ด้วย IQR
Q1 = df['salary'].quantile(0.25)
Q3 = df['salary'].quantile(0.75)
IQR = Q3 - Q1
lower = Q1 - 1.5 * IQR
upper = Q3 + 1.5 * IQR
outliers = df[(df['salary'] < lower) | (df['salary'] > upper)]
print(f"Outliers: {len(outliers)} rows")
# ลบ Outliers
df_clean = df[(df['salary'] >= lower) & (df['salary'] <= upper)]
# เปลี่ยนชื่อคอลัมน์
df = df.rename(columns={'salary': 'monthly_salary', 'age': 'employee_age'})
# ทำให้ข้อมูลเป็นรูปแบบเดียวกัน
df['city'] = df['city'].str.strip().str.lower() # ลบช่องว่าง + lowercase
df['name'] = df['name'].str.title() # Capitalize
Matplotlib — สร้าง Visualization
Matplotlib เป็น Library สำหรับสร้างกราฟที่เก่าแก่และยืดหยุ่นที่สุดใน Python สามารถสร้างกราฟได้ทุกประเภท ตั้งแต่ Line Chart ธรรมดาไปจนถึงกราฟ 3 มิติ แม้ Syntax จะยาวกว่า Library อื่น แต่ข้อดีคือปรับแต่งได้ทุกรายละเอียด
import matplotlib.pyplot as plt
import numpy as np
# Line Chart — กราฟเส้น
x = np.linspace(0, 10, 100)
plt.figure(figsize=(10, 6))
plt.plot(x, np.sin(x), label='sin(x)', color='blue', linewidth=2)
plt.plot(x, np.cos(x), label='cos(x)', color='red', linestyle='--')
plt.title('Sine vs Cosine', fontsize=16)
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('line_chart.png', dpi=150, bbox_inches='tight')
plt.show()
# Bar Chart — กราฟแท่ง
categories = ['Python', 'JavaScript', 'Java', 'C++', 'Go']
values = [85, 78, 65, 45, 55]
plt.figure(figsize=(8, 5))
colors = ['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6']
bars = plt.bar(categories, values, color=colors, edgecolor='black')
plt.title('Programming Language Popularity')
plt.ylabel('Score')
for bar, val in zip(bars, values):
plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 1,
str(val), ha='center', fontweight='bold')
plt.tight_layout()
plt.show()
# Scatter Plot — กราฟจุดกระจาย
np.random.seed(42)
x = np.random.randn(200)
y = x * 2 + np.random.randn(200) * 0.5
colors = np.random.rand(200)
plt.figure(figsize=(8, 6))
plt.scatter(x, y, c=colors, cmap='viridis', alpha=0.6, s=50)
plt.colorbar(label='Value')
plt.title('Scatter Plot with Color Map')
plt.xlabel('Feature X')
plt.ylabel('Feature Y')
plt.show()
# Histogram — ฮิสโตแกรม
data = np.random.normal(170, 10, 1000) # ส่วนสูง 1000 คน
plt.figure(figsize=(8, 5))
plt.hist(data, bins=30, color='skyblue', edgecolor='black', alpha=0.7)
plt.axvline(np.mean(data), color='red', linestyle='--', label=f'Mean: {np.mean(data):.1f}')
plt.title('Distribution of Heights')
plt.xlabel('Height (cm)')
plt.ylabel('Frequency')
plt.legend()
plt.show()
# Subplots — หลายกราฟในภาพเดียว
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('Line')
axes[0, 1].bar(['A', 'B', 'C'], [3, 7, 5])
axes[0, 1].set_title('Bar')
axes[1, 0].scatter(np.random.rand(50), np.random.rand(50))
axes[1, 0].set_title('Scatter')
axes[1, 1].hist(np.random.randn(500), bins=20)
axes[1, 1].set_title('Histogram')
plt.tight_layout()
plt.show()
Seaborn — Visualization ที่สวยงามกว่า
Seaborn สร้างอยู่บน Matplotlib แต่ให้ผลลัพธ์ที่สวยงามกว่าด้วยโค้ดที่สั้นกว่า เหมาะสำหรับ Statistical Visualization โดยเฉพาะ ทำงานร่วมกับ Pandas DataFrame ได้อย่างดีเยี่ยม และมี Theme ที่สวยงามเป็นค่าตั้งต้น
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# ตั้งค่า Style
sns.set_theme(style='whitegrid')
# ข้อมูลตัวอย่างจาก Seaborn
tips = sns.load_dataset('tips')
iris = sns.load_dataset('iris')
# Box Plot — แสดงการกระจายตัว
plt.figure(figsize=(8, 5))
sns.boxplot(x='day', y='total_bill', hue='sex', data=tips)
plt.title('Total Bill by Day and Gender')
plt.show()
# Violin Plot — แสดงการกระจายตัวแบบละเอียด
plt.figure(figsize=(8, 5))
sns.violinplot(x='day', y='total_bill', data=tips)
plt.title('Bill Distribution by Day')
plt.show()
# Heatmap — แสดงความสัมพันธ์
plt.figure(figsize=(8, 6))
corr = tips[['total_bill', 'tip', 'size']].corr()
sns.heatmap(corr, annot=True, cmap='coolwarm', center=0, fmt='.2f')
plt.title('Correlation Heatmap')
plt.show()
# Pair Plot — ดูความสัมพันธ์ทุกคู่
sns.pairplot(iris, hue='species', diag_kind='kde')
plt.show()
# Count Plot — นับจำนวน
plt.figure(figsize=(8, 5))
sns.countplot(x='day', hue='sex', data=tips, palette='Set2')
plt.title('Count by Day and Gender')
plt.show()
# Distribution Plot
plt.figure(figsize=(8, 5))
sns.histplot(tips['total_bill'], kde=True, bins=20)
plt.title('Distribution of Total Bill')
plt.show()
Exploratory Data Analysis (EDA) — ขั้นตอนการสำรวจข้อมูล
EDA คือกระบวนการสำรวจและทำความเข้าใจข้อมูลก่อนจะเริ่มสร้าง Model หรือวิเคราะห์เชิงลึก เป็นขั้นตอนที่สำคัญที่สุดใน Data Science Pipeline เพราะถ้าไม่เข้าใจข้อมูลดี ผลลัพธ์จะไม่น่าเชื่อถือ EDA ช่วยให้เราเห็นรูปแบบ ความผิดปกติ และความสัมพันธ์ในข้อมูล
# EDA Workflow ที่แนะนำ
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# 1. โหลดข้อมูล
df = pd.read_csv('sales_data.csv')
# 2. ดูข้อมูลเบื้องต้น
print("=== Shape ===")
print(df.shape)
print("\n=== First 5 Rows ===")
print(df.head())
print("\n=== Info ===")
df.info()
print("\n=== Describe ===")
print(df.describe())
# 3. ตรวจสอบ Missing Data
print("\n=== Missing Values ===")
missing = df.isnull().sum()
missing_pct = (missing / len(df) * 100).round(2)
missing_df = pd.DataFrame({'count': missing, 'percent': missing_pct})
print(missing_df[missing_df['count'] > 0])
# 4. ตรวจสอบ Data Types
print("\n=== Data Types ===")
print(df.dtypes)
# 5. ดู Unique Values ของ Categorical Columns
for col in df.select_dtypes(include='object').columns:
print(f"\n{col}: {df[col].nunique()} unique values")
print(df[col].value_counts().head())
# 6. Visualization
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Distribution ของ Numerical Columns
numeric_cols = df.select_dtypes(include=np.number).columns
for i, col in enumerate(numeric_cols[:4]):
ax = axes[i // 2, i % 2]
sns.histplot(df[col], kde=True, ax=ax)
ax.set_title(f'Distribution of {col}')
plt.tight_layout()
plt.show()
# 7. Correlation Matrix
plt.figure(figsize=(10, 8))
corr = df.select_dtypes(include=np.number).corr()
sns.heatmap(corr, annot=True, cmap='RdBu_r', center=0, fmt='.2f')
plt.title('Correlation Matrix')
plt.show()
โปรเจกต์จริง: วิเคราะห์ข้อมูลยอดขาย
มาลองทำโปรเจกต์จริงกัน สมมติว่าเราได้ข้อมูลยอดขายของร้านค้าออนไลน์ และต้องการวิเคราะห์เพื่อหา Insight ที่จะช่วยเพิ่มยอดขาย โปรเจกต์นี้จะใช้ทุก Skill ที่เรียนมา ตั้งแต่การโหลดข้อมูล ทำความสะอาด วิเคราะห์ และสร้าง Visualization
# สร้างข้อมูลตัวอย่างยอดขาย
import pandas as pd
import numpy as np
np.random.seed(42)
n = 1000
dates = pd.date_range('2025-01-01', periods=n, freq='D')
products = np.random.choice(['Laptop', 'Phone', 'Tablet', 'Headphone', 'Keyboard'], n)
regions = np.random.choice(['Bangkok', 'Chiang Mai', 'Phuket', 'Khon Kaen'], n)
quantities = np.random.randint(1, 20, n)
prices = {'Laptop': 35000, 'Phone': 15000, 'Tablet': 12000,
'Headphone': 2500, 'Keyboard': 1500}
unit_prices = [prices[p] for p in products]
sales_df = pd.DataFrame({
'date': dates[:n],
'product': products,
'region': regions,
'quantity': quantities,
'unit_price': unit_prices
})
sales_df['revenue'] = sales_df['quantity'] * sales_df['unit_price']
sales_df['month'] = sales_df['date'].dt.month
sales_df['day_of_week'] = sales_df['date'].dt.day_name()
# วิเคราะห์ 1: ยอดขายรายเดือน
monthly_revenue = sales_df.groupby('month')['revenue'].sum()
plt.figure(figsize=(10, 5))
monthly_revenue.plot(kind='bar', color='steelblue')
plt.title('Monthly Revenue')
plt.xlabel('Month')
plt.ylabel('Revenue (Baht)')
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()
# วิเคราะห์ 2: สินค้าขายดี
product_revenue = sales_df.groupby('product')['revenue'].sum().sort_values()
plt.figure(figsize=(8, 5))
product_revenue.plot(kind='barh', color=['#e74c3c', '#f39c12', '#2ecc71', '#3498db', '#9b59b6'])
plt.title('Revenue by Product')
plt.xlabel('Revenue (Baht)')
plt.tight_layout()
plt.show()
# วิเคราะห์ 3: ยอดขายตามภูมิภาค
region_stats = sales_df.groupby('region').agg({
'revenue': ['sum', 'mean'],
'quantity': 'sum'
}).round(0)
print(region_stats)
# วิเคราะห์ 4: แนวโน้มยอดขายรายวัน (Moving Average)
daily_revenue = sales_df.groupby('date')['revenue'].sum()
plt.figure(figsize=(14, 5))
plt.plot(daily_revenue.index, daily_revenue.values, alpha=0.3, label='Daily')
plt.plot(daily_revenue.rolling(window=7).mean(), color='red', linewidth=2, label='7-day MA')
plt.plot(daily_revenue.rolling(window=30).mean(), color='blue', linewidth=2, label='30-day MA')
plt.title('Daily Revenue with Moving Average')
plt.legend()
plt.show()
# วิเคราะห์ 5: Heatmap ยอดขายตามวัน x สินค้า
pivot = sales_df.pivot_table(values='revenue', index='day_of_week',
columns='product', aggfunc='mean')
plt.figure(figsize=(10, 6))
sns.heatmap(pivot, annot=True, fmt='.0f', cmap='YlOrRd')
plt.title('Average Revenue: Day of Week x Product')
plt.show()
Jupyter Notebook — เคล็ดลับสำหรับ Data Science
Jupyter Notebook เป็นเครื่องมือที่ขาดไม่ได้ในงาน Data Science ช่วยให้สามารถเขียนโค้ด ดูผลลัพธ์ สร้างกราฟ และเขียนบันทึกในเอกสารเดียว ทำให้งานวิเคราะห์เป็นแบบ Interactive ที่สามารถทดลองและปรับเปลี่ยนได้อย่างรวดเร็ว
# Magic Commands ที่มีประโยชน์
%timeit np.random.randn(1000) # วัดเวลา
%%time # วัดเวลาทั้ง Cell
%matplotlib inline # แสดงกราฟใน Notebook
%who # ดูตัวแปรทั้งหมด
%whos # ดูตัวแปรพร้อมรายละเอียด
%reset # ล้างตัวแปรทั้งหมด
%load_ext autoreload # Auto reload modules
%autoreload 2
# แสดง DataFrame สวยๆ
pd.set_option('display.max_columns', None) # แสดงทุกคอลัมน์
pd.set_option('display.max_rows', 100) # แสดง 100 แถว
pd.set_option('display.float_format', '{:.2f}'.format) # ทศนิยม 2 ตำแหน่ง
# Profiling Report อัตโนมัติ
# pip install ydata-profiling
from ydata_profiling import ProfileReport
profile = ProfileReport(df, title='Sales Data Report')
profile.to_notebook_iframe()
profile.to_file('report.html')
scikit-learn — เริ่มต้น Machine Learning
เมื่อเข้าใจ Pandas และ NumPy แล้ว ขั้นตอนถัดไปคือการเริ่มต้น Machine Learning ด้วย scikit-learn ซึ่งเป็น Library ที่ใช้ง่ายที่สุดสำหรับ ML ใน Python สอนวิธีแบ่งข้อมูล Train/Test, สร้าง Model และวัดผลเบื้องต้น
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
# สร้างข้อมูลตัวอย่าง
np.random.seed(42)
X = np.random.randn(500, 3)
y = 3 * X[:, 0] + 2 * X[:, 1] - X[:, 2] + np.random.randn(500) * 0.5
# แบ่ง Train/Test
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(f"Train: {X_train.shape}, Test: {X_test.shape}")
# Scaling (ปรับ Scale ข้อมูล)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Linear Regression
lr_model = LinearRegression()
lr_model.fit(X_train_scaled, y_train)
lr_pred = lr_model.predict(X_test_scaled)
# Random Forest
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
rf_model.fit(X_train_scaled, y_train)
rf_pred = rf_model.predict(X_test_scaled)
# วัดผล
for name, pred in [('Linear Regression', lr_pred), ('Random Forest', rf_pred)]:
rmse = np.sqrt(mean_squared_error(y_test, pred))
r2 = r2_score(y_test, pred)
print(f"{name}: RMSE={rmse:.4f}, R2={r2:.4f}")
Performance Tips — ทำให้โค้ดเร็วขึ้น
เมื่อทำงานกับข้อมูลขนาดใหญ่ Performance เป็นสิ่งสำคัญมาก การเขียนโค้ดที่ช้าจะทำให้เสียเวลาในการวิเคราะห์ และอาจทำให้ไม่สามารถประมวลผลข้อมูลได้ทันเวลา
# 1. ใช้ Vectorization แทน Loop เสมอ
# ช้า
result = []
for i in range(len(df)):
result.append(df.iloc[i]['price'] * df.iloc[i]['quantity'])
# เร็ว (100x+)
result = df['price'] * df['quantity']
# 2. ใช้ .apply() เมื่อจำเป็น (ช้ากว่า Vectorized แต่เร็วกว่า Loop)
df['category'] = df['price'].apply(lambda x: 'High' if x > 1000 else 'Low')
# 3. ใช้ np.where แทน apply สำหรับ Conditional
df['category'] = np.where(df['price'] > 1000, 'High', 'Low')
# 4. ระบุ dtype เมื่ออ่านไฟล์
df = pd.read_csv('large_data.csv', dtype={
'id': 'int32',
'name': 'category', # ประหยัด Memory สำหรับ String ซ้ำ
'value': 'float32'
})
# 5. อ่านเฉพาะคอลัมน์ที่ต้องการ
df = pd.read_csv('large_data.csv', usecols=['name', 'value'])
# 6. ใช้ Chunking สำหรับไฟล์ใหญ่มาก
chunks = pd.read_csv('huge_file.csv', chunksize=100000)
result = pd.DataFrame()
for chunk in chunks:
processed = chunk.groupby('category')['value'].sum()
result = pd.concat([result, processed])
# 7. ตรวจสอบ Memory Usage
print(df.memory_usage(deep=True).sum() / 1024**2, "MB")
Library ที่น่าสนใจในปี 2026
| Library | ใช้ทำอะไร | ข้อดี |
|---|---|---|
Polars | DataFrame แทน Pandas | เร็วกว่า 10-100x เขียนด้วย Rust |
DuckDB | SQL Engine ใน Python | Query ข้อมูลด้วย SQL โดยตรง เร็วมาก |
Plotly | Interactive Visualization | กราฟแบบ Interactive, Zoom, Hover |
Streamlit | สร้าง Web App | สร้าง Dashboard ด้วย Python อย่างเดียว |
ydata-profiling | Auto EDA Report | สร้างรายงาน EDA อัตโนมัติ |
PySpark | Big Data Processing | ประมวลผลข้อมูล TB ระดับ Distributed |
# ตัวอย่าง Polars — DataFrame ที่เร็วกว่า Pandas
import polars as pl
df = pl.read_csv('data.csv')
result = (
df.lazy()
.filter(pl.col('salary') > 40000)
.group_by('department')
.agg([
pl.col('salary').mean().alias('avg_salary'),
pl.col('name').count().alias('count')
])
.sort('avg_salary', descending=True)
.collect()
)
# ตัวอย่าง DuckDB — SQL ใน Python
import duckdb
result = duckdb.sql("""
SELECT department, AVG(salary) as avg_salary, COUNT(*) as count
FROM 'employees.csv'
WHERE salary > 40000
GROUP BY department
ORDER BY avg_salary DESC
""").df() # แปลงเป็น Pandas DataFrame
เส้นทางอาชีพ Data Science ในปี 2026
สาย Data Science มีหลายเส้นทางให้เลือก ขึ้นอยู่กับความสนใจและทักษะ ปัจจุบันทุกอุตสาหกรรมต้องการคนที่สามารถวิเคราะห์ข้อมูลได้ ไม่ว่าจะเป็นธนาคาร ค้าปลีก สุขภาพ หรือการผลิต
สำหรับ Data Analyst จะเน้นที่การวิเคราะห์ข้อมูลและสร้างรายงาน ต้องเก่ง SQL, Excel, Python/Pandas และเครื่องมือ BI เช่น Tableau หรือ Power BI เหมาะสำหรับผู้เริ่มต้นที่ต้องการเข้าสู่สาย Data
สำหรับ Data Scientist จะเน้นที่การสร้าง Model และหา Insight จากข้อมูล ต้องมีพื้นฐานสถิติ Machine Learning และ Deep Learning เงินเดือนสูงกว่า Data Analyst แต่ต้องมีทักษะมากกว่า
สำหรับ Data Engineer จะเน้นที่การสร้าง Pipeline สำหรับประมวลผลข้อมูล ต้องเก่ง Python, SQL, Spark, Airflow และ Cloud Platform เป็นตำแหน่งที่ขาดแคลนมากที่สุดในตลาดงาน
สำหรับ ML Engineer จะเน้นที่การนำ Model ไป Deploy ในระบบ Production ต้องเก่งทั้ง Data Science และ Software Engineering เป็นตำแหน่งที่มีเงินเดือนสูงที่สุดในสาย Data
สรุป
Python สำหรับ Data Science เป็นทักษะที่มีคุณค่าสูงมากในปี 2026 ไม่ว่าจะอยู่ในสายอาชีพใด การเข้าใจวิธีวิเคราะห์ข้อมูลจะช่วยให้ตัดสินใจได้ดีขึ้น เริ่มต้นด้วย NumPy เพื่อเข้าใจการคำนวณเชิงตัวเลข จากนั้นเรียน Pandas เพื่อจัดการข้อมูลแบบตาราง แล้วใช้ Matplotlib และ Seaborn เพื่อสร้าง Visualization สุดท้ายฝึกทำ EDA กับข้อมูลจริงเพื่อสร้างประสบการณ์
สิ่งสำคัญที่สุดคือการลงมือทำ ดาวน์โหลด Dataset จาก Kaggle หรือ UCI Machine Learning Repository แล้วเริ่มวิเคราะห์ เริ่มจากคำถามง่ายๆ เช่น ยอดขายเดือนไหนดีที่สุด สินค้าไหนขายดี ลูกค้ากลุ่มไหนใช้จ่ายมากที่สุด แล้วค่อยๆ เพิ่มความซับซ้อนขึ้นเรื่อยๆ Data Science ไม่ใช่เรื่องยาก เพียงแต่ต้องฝึกฝนอย่างสม่ำเสมอ
