Nội dung

1. Chuyển đổi kiểu dữ liệu

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ố.


1.1 Kiểm tra kiểu dữ liệu

Sử dụng:

df.dtypes

Ví dụ kết quả:

ColumnType
Priceobject
Ageint64
Salaryfloat64

1.2 Chuyển đổi kiểu dữ liệu

Sử dụng astype()

df["Age"] = df["Age"].astype(int)

Chuyển đổi sang số

pd.to_numeric()

Ví dụ:

df["Price"] = pd.to_numeric(df["Price"])

Chuyển đổi sang ngày tháng

pd.to_datetime()

Ví dụ:

df["Date"] = pd.to_datetime(df["Date"])

2. Xử lý dữ liệu chuỗi

Trong Pandas có thể xử lý chuỗi bằng str accessor.

Cú pháp:

df["column"].str.method()

2.1 Chuyển chữ hoa / chữ thường

df["Name"].str.lower()
df["Name"].str.upper()

2.2 Xóa khoảng trắng

df["Name"].str.strip()

2.3 Thay thế chuỗi

df["Price"].str.replace("$","")

2.4 Tách chuỗi

Ví dụ cột ngày:

2024-03-10

Tách thành:

  • Year

  • Month

  • Day

df["Date"].str.split("-")

3. Chuẩn hóa dữ liệu giá tiền

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)

4. Phát hiện dữ liệu ngoại lệ (Outliers)

Outliers là giá trị bất thường trong dữ liệu.

Ví dụ:

Age
25
30
28
120

120 là outlier.


4.1 Phương pháp IQR

IQR = Q3 – Q1

Trong đó:

  • Q1: quartile 1

  • Q3: quartile 3


Công thức phát hiện outliers

Outlier nếu:

value < Q1 - 1.5 * IQR

hoặc

value > Q3 + 1.5 * IQR

Ví dụ trong Pandas

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)]

III. LÝ THUYẾT LIÊN QUAN

1. Kiểu dữ liệu trong Pandas

Các kiểu dữ liệu phổ biến:

TypeÝ nghĩa
intsố nguyên
floatsố thực
objectchuỗi
datetimengày tháng
boolTrue / False

2. Tác động của Outliers

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ỏ.


IV. TRÌNH TỰ THỰC HIỆN

Bước 1: Import thư viện

import pandas as pd

Bước 2: Đọc dữ liệu

df = pd.read_csv("sales.csv")

Bước 3: Kiểm tra kiểu dữ liệu

df.dtypes

Bước 4: Chuẩn hóa dữ liệu giá tiền

df["Price"] = df["Price"].str.replace("$","")
df["Price"] = df["Price"].str.replace(",","")
df["Price"] = df["Price"].astype(int)

Bước 5: Chuyển đổi ngày tháng

df["Date"] = pd.to_datetime(df["Date"])

Bước 6: Phát hiện Outliers

Q1 = df["Revenue"].quantile(0.25)
Q3 = df["Revenue"].quantile(0.75)

IQR = Q3 - Q1