
Hệ thống quản trị đào tạo trực tuyến
Trong dataset thực tế, dữ liệu thường không đúng kiểu.
Ví dụ:
| Price |
|---|
| $1,000 |
| $500 |
| $2,300 |
Dữ liệu này là chuỗi, không phải số.
Do đó cần chuyển đổi sang kiểu số.
Sử dụng:
df.dtypes
Ví dụ kết quả:
| Column | Type |
|---|---|
| Price | object |
| Age | int64 |
| Salary | float64 |
astype()df["Age"] = df["Age"].astype(int)
pd.to_numeric()
Ví dụ:
df["Price"] = pd.to_numeric(df["Price"])
pd.to_datetime()
Ví dụ:
df["Date"] = pd.to_datetime(df["Date"])
Trong Pandas có thể xử lý chuỗi bằng str accessor.
Cú pháp:
df["column"].str.method()
df["Name"].str.lower()
df["Name"].str.upper()
df["Name"].str.strip()
df["Price"].str.replace("$","")
Ví dụ cột ngày:
2024-03-10
Tách thành:
Year
Month
Day
df["Date"].str.split("-")
Ví dụ dữ liệu:
| Price |
|---|
| $1,200 |
| $900 |
| $3,500 |
Cần chuyển thành:
| Price |
|---|
| 1200 |
| 900 |
| 3500 |
Ví dụ xử lý:
df["Price"] = df["Price"].str.replace("$","")
df["Price"] = df["Price"].str.replace(",","")
df["Price"] = df["Price"].astype(int)
Outliers là giá trị bất thường trong dữ liệu.
Ví dụ:
| Age |
|---|
| 25 |
| 30 |
| 28 |
| 120 |
120 là outlier.
IQR = Q3 – Q1
Trong đó:
Q1: quartile 1
Q3: quartile 3
Outlier nếu:
value < Q1 - 1.5 * IQR
hoặc
value > Q3 + 1.5 * IQR
Q1 = df["Salary"].quantile(0.25)
Q3 = df["Salary"].quantile(0.75)
IQR = Q3 - Q1
outliers = df[(df["Salary"] < Q1 - 1.5*IQR) | (df["Salary"] > Q3 + 1.5*IQR)]
Các kiểu dữ liệu phổ biến:
| Type | Ý nghĩa |
|---|---|
| int | số nguyên |
| float | số thực |
| object | chuỗi |
| datetime | ngày tháng |
| bool | True / False |
Outliers có thể:
Làm sai lệch giá trị trung bình
Làm sai kết quả mô hình Machine Learning
Do đó cần:
Phát hiện
Xử lý
hoặc loại bỏ.
import pandas as pd
df = pd.read_csv("sales.csv")
df.dtypes
df["Price"] = df["Price"].str.replace("$","")
df["Price"] = df["Price"].str.replace(",","")
df["Price"] = df["Price"].astype(int)
df["Date"] = pd.to_datetime(df["Date"])
Q1 = df["Revenue"].quantile(0.25)
Q3 = df["Revenue"].quantile(0.75)
IQR = Q3 - Q1