1. Data Loading & Handling (Pandas)
Import modules
Dictionary to
DataFrame
Read CSV
import pandas as pd
pd.DataFrame(data)
Loads the library for use.
Turn a dictionary into a DataFrame
df = pd.read_csv("path/file.csv")
Loads a CSV file into a DataFrame.
Read No Header
pd.read_csv("...", header=None)
Set Headers
df.columns = ["Col1", "Col2", ...]
Export CSV
df.to_csv("path/new_file.csv")
Loads data that doesn't have
column names.
Assigns a list of names to the
DataFrame columns.
Saves the modified DataFrame back
to a file.
Reads JSON or Excel files.
Other Formats
pd.read_json()
pd.read_excel()
2. Data Inspection & Cleaning (pandas)
View Top Rows
df.head(n)
Interger
Location
Loc
Check Types
df.iloc[row_selection, column_selection]
chọn nhiều row bất kì: df.iloc[[row_1,
row_2]]
chọn nhiều row liên tiếp:
df.iloc[row_1:row_2]
df.loc[row_selection, column selection]
df.dtypes
Check Size
df.shape
Summary Stats
df.describe()
Drop Missing
df.dropna(subset=["col"], axis=0)
Replace Values
df.replace(old_val, new_val)
Rename Cols
Change Type
df.rename(columns={"old": "new"})
df["col"].astype("int")
3. Data Pre-processing (pandas, numpy)
Shows the first n rows of
the data.
Select data by index
number
Returns data types (int,
float, object) of columns.
Returns tuple (rows,
columns).
Returns count, mean, std,
min, max for numerical
cols.
Removes rows (axis=0)
with missing values in
"col".
Replaces specific values
(e.g., np.nan) with others.
Renames specific columns.
Converts a column's data
type (e.g., to integer).
Binning
Cut Data
One-Hot
Encoding
bins = np.linspace(min, max, n)
tự chọn bin: bins = [n, m,…]
pd.cut(df['col'], bins, labels=names,
include_lowest = True)
pd.get_dummies(df['col'])
Creates n dividing points
for bins.
Segments continuous data
into categorical bins.
Converts categorical
variables into dummy (0/1)
vars.
4. Exploratory Data Analysis (EDA) (pandas, scipy.stats)
Count Values
Grouping
Pivot Table
Correlation
Pearson Corr
df["col"].value_counts()
df.groupby(["col1"],
as_index=False).mean()
df.pivot(index="col1",
columns="col2")
Cho cả DataFrame: df.corr()
Cho 2 biến: df[“col1”].corr(df[“col2”])
stats.pearsonr(df['col1'], df['col2'])
Groups data by category
and calculates the mean.
Reshapes data into a grid
format.
Calculates correlation
matrix.
Returns Pearson coefficient
and P-value.
5. Data Visualization (matplotlib, seaborn)
Bar plot
sns.barplot(x=”col1”, y=”col2”, data=df)
plt.title(“…”)
plt.xlabel(“…”)
plt.ylabel(“…”)
plt.show()
plt.figure(figsize=(10, 6))
Scatter Plot
sns.scatterplot(x=“col1”, y=“col2”,
data=df
Box Plot
sns.boxplot(x="col1", y="col2", data=df)
sns.boxplot(y=df[“col2”])
Regression Plot sns.regplot(x="col1", y="col2", data=df)
Residual Plot
sns.residplot(df['x'], df['y'])
Plots data points to show
relationship.
visualizes distribution and
outliers.
Scatter plot with a linear
regression line fitted.
Plots the errors
(residuals) to check for
linearity.
Distribution
sns.distplot(df['col'], hist=False)
Histogram
Line Graph
sns.histplot(data=df, x="units_sold")
sns.lineplot(data=df, x="thời_gian",
y="giá_trị")
plt.pcolor(df_pivot, cmap='RdBu')
Heatmap
Plots the curve of the
data distribution.
Plots a color-coded matrix
(useful for correlation).
6. Model Development (sklearn)
Linear Model
Train Model
lm = LinearRegression()
X = df[[col1]] (2 ngoặc)
Y = df[col2] (1 ngoặc)
lm.fit(X, Y)
Creates a linear regression
object.
Trains the model on features X
and target Y.
Predict
Yhat = lm.predict(X)
Generates predictions using
the trained model.
Coefficients
lm.coef_[0] / lm.intercept_
Retrieves the slope (b1) and
intercept (b0).
Polynomial
pr = PolynomialFeatures(degree=n) Creates a transformer for
curved/polynomial fits.
Transform
pr.fit_transform(X)
Converts X into polynomial
features (X, X2,…)
Scaling
StandardScaler()
Standardizes features (Z-score
normalization).
Pipeline
Pipeline(steps=[('name', object), ...]) Bundles preprocessing and
modeling into one step.
7. Model Evaluation (sklearn.metrics)
MSE
R-Squared
Confusion
Matrix
mean_squared_error(Y_true, Y_pred) Calculates the Mean Squared
Error.
lm.score(X, Y)
Returns the R2 accuracy score
(0 to 1).
confusion_matrix(y_true, y_pred)
Shows True/False
Positives/Negatives (for
Classification).
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.metrics import mean_squared_error, r2_score, confusion_matrix
Xử lý string
Indexing:
s[0]: kí tự đầu
s[-1]: kí tự cuối
s[1:5]: lấy kí tự đầu đến sát 5
s[::-1]: đảo ngược chuỗi
Methods:
s.split(): tách chuỗi thành list
“ ”.join(list): nối list thành chuỗi
s.lower(): chuyển hết thành chữ thường
s.upper(): chuyển hết thành chữ hoa
s.title(): viết hoa mỗi chữ đầu
s.strip(): xóa khoảng trắng ở đầu và đuôi
s.replace(“old”, “new”): trả về chuỗi mới đã thay
s.find(“x”): trả về vị trí index của x
s.count(“x”): đếm số lần xuất hiện của x
len(s): độ dài chuỗi
Kiểm tra:
"a" in s: Kiểm tra có chứa "a" không.
s.isdigit(): Có phải toàn số không?
s.isalpha(): Có phải toàn chữ cái không?
s.startswith("x"): Có bắt đầu bằng "x" không?
o s.endswith(“x”)
Xử lý list
Indexing:
L[0]: phần tử đầu
L[1:3]: cắt ra list con tới sát 3
L[i] = giá_trị_mới: thay phần tử tại i
Methods:
L.append(x): thêm phần tử x vào đuôi
L.extend([x, y]): thêm 1 list vào đuôi
L.insert(index, x): thêm x vào vị trí index
L.pop(index): xóa phần tử tại vị trí index (mặc định là cuối)
L.remove(x): xóa phần tử đầu tiên có giá trị là x
L.sort(): sắp xếp list hiện tại (thay đổi trực tiếp L)
sorted(L): trả về list khác đã sắp xếp
L.reverse(): đảo ngược thứ tự list
max(L), min(L), sum(L): tìm lớn nhất, nhỏ nhất, tổng (chỉ với list số)
“ ”.join(list): nối list thành chuỗi
list(x): biến string, tuple, set, range, dictionary (chỉ lấy key) thành list
for x, y in enumerate(L): … trả về cả index và phần tử
Comprehension:
L = [expression for biến in list if điều kiện]
Xử lý tuple và set
Unpack tuple:
point = (10, 20) -> x, y = point (x=10, y=20): tự động assign x và y
Xử lý dictionary
Indexing:
d[“ten_key”]: trả về value tương ứng (hay lỗi)
o d.get[“ten_key”]
d[“ten_key”] = x: nếu tên key đã tồn tại, thay value bằng x, nếu chưa tồn tại, thêm
key và value mới
del d[“ten_key”]: xóa cặp key và value
Methods:
d.keys(): trả về list các key
d.values(): trả về list các value
d.items(): trả về cả key và value (chạy vòng lặp for k, v)
Comprehension:
{key: value for bien in L if dieu_kien}
{key: value for key, value in d if dieu_kien}