鋼鐵 V 走闖職場
數據

Python 探索式資料分析(EDA):資料驗證、清理到特徵工程,附英國零售實際案例

↑ 目錄

這篇整理自我在 DataCamp 學習《Exploratory Data Analysis in Python》的筆記,最後附上一個我用真實公開資料實際跑出來的案例分析。

探索式資料分析(Exploratory Data Analysis,EDA)是任何資料專案的第一步:先搞懂資料長什麼樣子、有沒有問題,再決定要怎麼分析。這門課的流程可以濃縮成四件事:認識資料 → 清理與補值 → 找出模式與關聯 → 產生新特徵與假設。

先看這裡:這篇適合誰、要先會什麼

  • 適合誰:剛接觸 pandas,不確定「拿到一份資料,第一步該做什麼」的人。
  • 先備知識:會安裝 Python、能在 Jupyter Notebook 或 VS Code 執行程式,知道什麼是「欄位」和「列」就夠了,不需要統計背景。
  • 你會學到:
    1. 用 .info()、.describe() 快速檢查一份資料
    2. 資料常見的三大問題:型態不對、缺失值、離群值,各自怎麼處理
    3. 找出相關性、時間型態與新特徵
    4. 用真實的 54 萬筆零售資料,完整跑一次這個流程

建議閱讀順序(這個系列由淺入深):

  1. 探索式資料分析(EDA)(你在這裡):先學會看懂、清理資料
  2. 資料視覺化(Seaborn):把資料畫成一眼看懂的圖
  3. 客戶分群(Cohort、RFM、K-means):找出不同類型的客戶
  4. 購物籃分析(Apriori):找出常一起買的商品
  5. 客戶流失預測:用機器學習預測誰會離開
  6. 客戶分析與 A/B 測試:用實驗驗證行動有沒有效

Chapter 1:認識資料集

初步探索

# 讀取資料
import pandas as pd
books = pd.read_csv("books.csv")
books.head()  # 看資料表前幾列

# 快速摘要:欄位、缺失資訊、資料型態與記憶體用量
books.info()
books["genre"].value_counts()  # 每個類別各有幾筆資料
books.describe()               # 快速取得統計數據

# 視覺化數值型資料
import seaborn as sns
import matplotlib.pyplot as plt
sns.histplot(data=books, x="rating", binwidth=1)
plt.show()

資料驗證(Data Validation)

# 檢查資料型態
books.dtypes

# 轉換資料型態(int / str / float / dict / list / bool)
books["year"] = books["year"].astype("float")

# 驗證類別資料
books["genre"].isin(["Fiction", "Non Fiction"])
~books["genre"].isin(["Fiction", "Non Fiction"])                 # 用 ~ 反向選取
books[books["genre"].isin(["Fiction", "Non Fiction"])].head()    # 布林值當作篩選條件

# 驗證數值資料
books.select_dtypes("number").head()
books["year"].min()   # 年份最小值
books["year"].max()   # 年份最大值
sns.boxplot(data=books, x="year", y="genre")

資料彙總(Data Summarization)

.groupby() 用來分組,aggregating function(聚合函數)則決定怎麼彙總每一組。

books.groupby("genre").mean(numeric_only=True)

# .agg() 可以一次套用多個聚合函數(只適用於數值欄位)
books.agg(["mean", "min"], numeric_only=True)
books.agg({"rating": ["mean", "std"], "year": ["median"]})

# 具名彙總:讓輸出欄位更好讀
books.groupby("genre").agg(
    mean_rating=("rating", "mean"),
    std_rating=("rating", "std"),
    median_year=("year", "median"),
)

# 視覺化類別資料:長條圖會自動算平均數並畫出 95% 信賴區間
sns.barplot(data=books, x="genre", y="rating")
plt.show()

Chapter 2:資料清理與補值

處理缺失值

為什麼要處理缺失值?因為它會影響資料的分布與後續的分析結果。常見做法:

  • 缺失筆數少於總資料的 5%:直接刪除。
  • 用平均數、中位數或眾數補值:要視情境與資料分布而定。
  • 依子群組補值:例如不同經驗等級的薪水中位數本來就不同。
# 檢查缺失值
print(salaries.isna().sum())

# 門檻:總筆數的 5%
threshold = len(salaries) * 0.05
cols_to_drop = salaries.columns[salaries.isna().sum() <= threshold]
salaries.dropna(subset=cols_to_drop, inplace=True)

# 其餘缺失欄位用平均數補值(最後一欄通常是類別欄位,不適合取平均)
cols_with_missing_data = salaries.columns[salaries.isna().sum() > 0]
for col in cols_with_missing_data[:-1]:
    salaries[col] = salaries[col].fillna(salaries[col].mean())

# 依子群組補值:先算各經驗等級的薪水中位數,再依群組補上
salary_dict = salaries.groupby("Experience")["Salary_USD"].median().to_dict()
salaries["Salary_USD"] = salaries["Salary_USD"].fillna(salaries["Experience"].map(salary_dict))

轉換並分析類別資料

# 預覽類別(object)欄位
print(salaries.select_dtypes("object").head())

# 不重複值的數量
print(salaries["Designation"].nunique())

# 用字串比對從類別欄位萃取資訊
salaries["Designation"].str.contains("Scientist")               # 包含某字
salaries["Designation"].str.contains("Machine Learning|AI")     # 多個關鍵字(| 代表「或」)
salaries["Designation"].str.contains("^Data")                   # 以 Data 開頭

# 建立新的類別欄位
import numpy as np
conditions = [
    salaries["Designation"].str.contains("Data Scientist|NLP"),
    salaries["Designation"].str.contains("Analyst|Analytics"),
    salaries["Designation"].str.contains("Machine Learning|AI"),
]
job_categories = ["Data Science", "Data Analytics", "Machine Learning"]
salaries["Job_Category"] = np.select(conditions, job_categories, default="Other")
print(salaries[["Designation", "Job_Category"]].head())

處理數值資料

# 字串轉數值:先去掉千分位逗號
salaries["Salary_In_Rupees"] = salaries["Salary_In_Rupees"].str.replace(",", "")
salaries["Salary_In_Rupees"] = salaries["Salary_In_Rupees"].astype(float)

# 1 印度盧比 = 0.012 美元
salaries["Salary_USD"] = salaries["Salary_In_Rupees"] * 0.012
print(salaries[["Salary_In_Rupees", "Salary_USD"]].head())

# 把彙總統計加進原本的 DataFrame
salaries.groupby("Company_Size")["Salary_USD"].mean()
salaries["std_dev"] = salaries.groupby("Experience")["Salary_USD"].transform(lambda x: x.std())
print(salaries[["Experience", "std_dev"]].value_counts())

處理離群值(Outlier)

離群值是遠離其他資料點的觀測值。判斷方式是用箱型圖的 IQR(四分位距):

  • IQR = 第 75 百分位數 − 第 25 百分位數
  • 上界 = 第 75 百分位數 + 1.5 × IQR
  • 下界 = 第 25 百分位數 − 1.5 × IQR
print(salaries["Salary_USD"].describe())

# 用箱型圖看 IQR
sns.boxplot(data=salaries, y="Salary_USD")
plt.show()

# 計算門檻
seventy_fifth = salaries["Salary_USD"].quantile(0.75)
twenty_fifth = salaries["Salary_USD"].quantile(0.25)
salaries_iqr = seventy_fifth - twenty_fifth
upper = seventy_fifth + (1.5 * salaries_iqr)
lower = twenty_fifth - (1.5 * salaries_iqr)
print(upper, lower)

# 篩出離群值
salaries[(salaries["Salary_USD"] < lower) | (salaries["Salary_USD"] > upper)][
    ["Experience", "Employee_Location", "Salary_USD"]
]

Chapter 3:隨時間變化的模式、相關性與分布

時間型態

divorce = pd.read_csv("divorce.csv")

# 讀檔時就解析日期
divorce = pd.read_csv("divorce.csv", parse_dates=["marriage_date"])

# 或是事後轉換成 datetime
divorce["marriage_date"] = pd.to_datetime(divorce["marriage_date"])

# 由年月日欄位組合成日期
divorce["marriage_date"] = pd.to_datetime(divorce[["month", "day", "year"]])

# 取出日期的一部分(dt.month / dt.day / dt.year)
divorce["marriage_month"] = divorce["marriage_date"].dt.month

# 視覺化:各月份結婚的平均婚姻長度
sns.lineplot(data=divorce, x="marriage_month", y="marriage_duration")
plt.show()

相關性(Correlation)

  • 描述兩個變數之間關係的方向與強度。
  • 可以協助預測未來的結果。
# .corr() 計算皮爾森相關係數,衡量的是「線性」關係
divorce.corr(numeric_only=True)

# 相關性熱圖
sns.heatmap(divorce.corr(numeric_only=True), annot=True)
plt.show()

divorce["divorce_date"].min()
divorce["divorce_date"].max()

# 散佈圖比較兩個變數
sns.scatterplot(data=divorce, x="income_man", y="income_woman")
plt.show()

# 用 pairplot 一次看多個變數兩兩之間的關係
sns.pairplot(data=divorce, vars=["income_man", "income_woman", "marriage_duration"])
plt.show()

因子之間的關係與分布

# 男方的教育程度分布
divorce["education_man"].value_counts()

# 想看資料分布,先用 histplot 快速檢視
sns.histplot(data=divorce, x="marriage_duration", binwidth=1)
plt.show()

# 用 hue 依類別分層
sns.histplot(data=divorce, x="marriage_duration", hue="education_man", binwidth=1)
plt.show()

# 核密度估計圖(KDE)
sns.kdeplot(data=divorce, x="marriage_duration", hue="education_man")
plt.show()

# KDE + cut=0(去掉負值的部分)+ cumulative(累積分布)
sns.kdeplot(data=divorce, x="marriage_duration", hue="education_man", cut=0, cumulative=True)
plt.show()

# 新增特徵:結婚時的年齡
divorce["man_age_marriage"] = divorce["marriage_year"] - divorce["dob_man"].dt.year
divorce["woman_age_marriage"] = divorce["marriage_year"] - divorce["dob_woman"].dt.year

# 帶有類別變數的散佈圖
sns.scatterplot(data=divorce, x="woman_age_marriage", y="man_age_marriage", hue="education_man")
plt.show()

類別資料的考量:交叉表(Cross Tabulation)

# 各職務類別的相對次數
print(salaries["Job_Category"].value_counts(normalize=True))

# 用 pd.crosstab() 彙總:出發地 × 目的地的價格中位數
pd.crosstab(planes["Source"], planes["Destination"],
            values=planes["Price"], aggfunc="median")

產生新特徵

# 清理「轉機次數」欄位
planes["Total_Stops"] = planes["Total_Stops"].str.replace(" stops", "")
planes["Total_Stops"] = planes["Total_Stops"].str.replace(" stop", "")
planes["Total_Stops"] = planes["Total_Stops"].str.replace("non-stop", "0")
planes["Total_Stops"] = planes["Total_Stops"].astype(int)

# 相關性熱圖
sns.heatmap(planes.corr(numeric_only=True), annot=True)
plt.show()

# 取出月份與星期幾
planes["month"] = planes["Date_of_Journey"].dt.month
planes["weekday"] = planes["Date_of_Journey"].dt.weekday
print(planes[["month", "weekday", "Date_of_Journey"]].head())

# 依價格百分位數建立價格等級
print(planes["Price"].describe())
twenty_fifth = planes["Price"].quantile(0.25)
median = planes["Price"].median()
seventy_fifth = planes["Price"].quantile(0.75)
maximum = planes["Price"].max()

labels = ["Economy", "Premium Economy", "Business Class", "First Class"]
bins = [0, twenty_fifth, median, seventy_fifth, maximum]
planes["Price_Category"] = pd.cut(planes["Price"], labels=labels, bins=bins)

print(planes[["Price", "Price_Category"]].head())
sns.countplot(data=planes, x="Airline", hue="Price_Category")
plt.show()

產生假設

EDA 的最後一步,是把發現的模式變成可以驗證的假設,再交給統計檢定或機器學習去檢驗。

下一步學習:

  1. Sampling in Python(抽樣)
  2. Hypothesis Testing in Python(假設檢定)
  3. Supervised Learning with scikit-learn(監督式學習)

初學者補充:環境、速查表與常見錯誤

先把環境準備好

pip install pandas seaborn matplotlib openpyxl

openpyxl 是為了讀 Excel 檔(下面的案例資料是 .xlsx)。課程範例用的書籍、薪資、航班資料集來自 DataCamp,沒辦法自己下載練習,想動手跑,請直接用下面「實際案例」的公開資料:

import pandas as pd

# 到 UCI 下載「Online Retail」資料集(https://archive.ics.uci.edu/dataset/352/online+retail),
# 解壓縮後放在和程式相同的資料夾
df = pd.read_excel("Online Retail.xlsx")
df.head()

我想知道……,該用哪個指令?

我想知道…常用指令
資料有幾列幾欄df.shape
每個欄位的型態、有沒有缺失df.info()
數值欄位的平均、最大、最小、四分位數df.describe()
某個類別欄位每種類別有幾筆df["欄位"].value_counts()
每個欄位缺失幾筆df.isna().sum()
刪除或補上缺失值df.dropna() / df.fillna(值)
依類別彙總(平均、加總、筆數)df.groupby("欄位").agg(...)
找離群值箱型圖 + IQR(上界 = Q3 + 1.5 × IQR)
兩個數值變數的關係df.corr()、sns.scatterplot()
把連續數字切成區間pd.cut()(自訂切點)、pd.qcut()(等人數)

初學者最常踩的坑

  1. 沒先看資料型態就開始算:數字被讀成字串(例如 "1,200"),mean() 直接報錯或算出怪結果。先 df.info(),必要時 .astype()。
  2. 用平均數補缺失值,卻沒看分布:有離群值時平均數會被拉高,偏態資料通常用中位數補比較穩。
  3. 看到離群值就刪:離群值可能是「資料錯誤」,也可能是「真實的極端情況」(例如批發客一次買 1,000 件),處理方式不同,先弄清楚是哪一種再決定。
  4. 看趨勢前沒確認資料涵蓋的期間:最後一個月只有半個月資料,就會被誤讀成「營收下滑」。
  5. 篩選後直接修改,出現 SettingWithCopyWarning:篩選出來的子集要先 .copy() 再改。
  6. 只做一次就以為好了:EDA 是反覆的過程,每次清理之後都要重新檢查一次。

實際案例:用 EDA 檢視英國網路零售的 54 萬筆交易

課程的範例資料(書籍、薪資、航班)都比較小。我另外找了真實的大資料集:UCI 機器學習資料庫的 Online Retail,這是一家英國網路禮品批發商在 2010 年 12 月到 2011 年 12 月之間的所有交易紀錄。我用上面學到的流程完整跑了一遍。以下數字都是實際執行的結果。

1. 先認識資料

  • 共 541,909 筆 × 8 欄(發票號碼、商品代碼、商品名稱、數量、日期、單價、客戶 ID、國家)
  • 期間:2010-12-01 到 2011-12-09,共 4,372 位客戶、25,900 張發票、4,070 種商品、38 個國家
  • 缺失值:CustomerID 缺 135,080 筆(24.93%),Description 缺 1,454 筆(0.27%)

缺失超過 5%,不能直接刪除。我先把缺 CustomerID 的交易保留,只在需要客戶層級分析的時候再排除,後面也量化了它的影響。

2. 資料驗證:藏著三個陷阱

df["InvoiceNo"] = df["InvoiceNo"].astype(str)
cancel = df["InvoiceNo"].str.startswith("C")     # 以 C 開頭 = 取消單

print(cancel.sum(), cancel.mean())               # 9,288 筆,1.71%
print((df["Quantity"] < 0).sum())                # 10,624 筆負數量
print(((df["Quantity"] < 0) & ~cancel).sum())    # 其中 1,336 筆不是取消單(多為庫存調整、報損)
print((df["UnitPrice"] <= 0).sum())              # 2,517 筆單價為 0

最容易漏掉的是第三個陷阱:取消單和它對應的原訂單要一起處理。我一開始只移除了取消單,結果發現資料裡最大的兩筆訂單(一筆 80,995 件、一筆 74,215 件)都是客戶下單後十幾分鐘就整筆取消,但原訂單還留在資料裡,會把營收灌水。修正後的做法是:找出每筆取消單對應的原訂單(同一客戶、同商品、同數量),一起移除。

def clean_retail(df):
    """移除取消單、負數量、單價 <= 0,並連同「被取消的原訂單」一起移除"""
    df = df.copy()
    df["InvoiceNo"] = df["InvoiceNo"].astype(str)
    cancel = df["InvoiceNo"].str.startswith("C")
    pos = df[~cancel & (df["Quantity"] > 0) & (df["UnitPrice"] > 0)].copy()

    # 取消單:把數量轉成正數,才能和原訂單對得起來
    canc = df[cancel & df["CustomerID"].notna()].copy()
    canc["Quantity"] = -canc["Quantity"]

    key = ["CustomerID", "StockCode", "Quantity"]
    n_cancel = canc.groupby(key).size().rename("n_cancel").reset_index()
    pos = pos.merge(n_cancel, on=key, how="left")
    pos["n_cancel"] = pos["n_cancel"].fillna(0)

    # 每組鍵值中,最近的 n 筆原訂單視為「被取消」
    pos = pos.sort_values("InvoiceDate", ascending=False)
    pos["rank_latest"] = pos.groupby(key, dropna=False).cumcount() + 1
    matched = (pos["n_cancel"] > 0) & (pos["rank_latest"] <= pos["n_cancel"]) & pos["CustomerID"].notna()
    return pos[~matched].drop(columns=["n_cancel", "rank_latest"]).sort_index()

clean = clean_retail(df)   # 共移除 3,188 筆被取消的原訂單,約 £479,139 的營收

清理完剩下 526,916 筆,總營收 £10,187,545。缺 CustomerID 的交易占營收的 17.2%,所以如果直接丟掉這些資料做客戶分析,等於少看了六分之一的營收。

3. 離群值:最大的「營收」竟然不是商品

for col in ["Quantity", "UnitPrice"]:
    q1, q3 = clean[col].quantile([0.25, 0.75])
    upper = q3 + 1.5 * (q3 - q1)
    print(col, upper, (clean[col] > upper).mean())
  • 數量:中位數只有 3,平均 10.17,IQR 上界是 23.5,有 10.6% 的明細超過上界。批發客戶一次買幾十件很正常,所以這裡的「離群」是業務特性,不是錯誤。
  • 單價:上界 £8.45,7.1% 超過。最高單價 £13,541.33,這筆是 AMAZON FEE;第二高 £11,062.06 是 Adjust bad debt。它們是會計調整項目,不是商品,會讓平均單價失真(平均 £3.81,但標準差高達 £32.34)。

單價與數量的箱型圖(對數座標)

這是 EDA 最有價值的發現之一:離群值要先判斷「是真的極端交易」還是「資料裡混進了不該有的東西」,處理方式完全不同。

4. 時間型態:旺季集中在年底

clean["Revenue"] = clean["Quantity"] * clean["UnitPrice"]
clean["Month"] = clean["InvoiceDate"].dt.to_period("M")
clean["Weekday"] = clean["InvoiceDate"].dt.day_name()
clean["Hour"] = clean["InvoiceDate"].dt.hour
clean.groupby("Month")["Revenue"].sum()
  • 2011 年 9 月到 11 月營收快速爬升:£1.05M → £1.11M → £1.49M(全年最高,11 月),是年初到年中每月 £0.5M–0.8M 的兩倍左右,符合聖誕節前備貨的批發旺季。
  • 12 月只有 £466,786,但這個數字不能拿來比較,因為資料只到 12 月 9 日。
  • 一週裡完全沒有週六的交易;週四營收最高(£2.17M),週日最低(£0.80M)。一天之中最強的是 12 點(£1.43M)、10 點(£1.34M)、15 點(£1.30M)。

月營收與星期 × 小時熱圖

5. 彙總、相關性與新特徵

by_country = clean.groupby("Country").agg(
    revenue=("Revenue", "sum"),
    orders=("InvoiceNo", "nunique"),
    customers=("CustomerID", "nunique"),
)
by_country["aov"] = by_country["revenue"] / by_country["orders"]
  • 英國占 91.4% 的交易筆數,但只占 84.4% 的營收。荷蘭只有 9 位客戶、94 張訂單,平均每張訂單卻高達 £3,032(英國是 £481),代表海外客戶是少量但大額的批發客。
  • 相關係數:數量與營收 0.58,單價與營收 0.46,單價與數量幾乎無關(−0.02),代表這家店不是「便宜所以買得多」,而是兩種購買型態並存。

用課程教的 pd.cut() 把單價依四分位數切成三個等級(£1.25 以下、£1.25–£4.13、£4.13 以上):

單價等級明細筆數營收營收占比平均每筆數量
低價161,944£1.92M18.8%17.2
中價240,707£4.59M45.1%8.6
高價124,265£3.68M36.1%4.0

低價品買得最多(平均 17 件),但營收貢獻只有 19%;中價商品是營收的主力,接近一半。

這個案例教我的事

  1. 缺失值超過 5% 就不能直接刪,要量化影響(這裡是 17.2% 的營收)。
  2. 取消單、庫存調整、會計科目這類「非真實銷售」的資料,會悄悄扭曲營收、平均值與離群值,必須先驗證再分析。
  3. 看時間趨勢前先確認資料的涵蓋範圍,否則會把「資料還沒結束」誤解成「營收下滑」。
  4. 下一步可以把「中價商品是主力」和「海外大額客戶」當成假設,用抽樣與假設檢定去驗證,這也正是課程接下來要學的內容。

資料來源:UCI Machine Learning Repository 的「Online Retail」公開資料集。分析使用 Python 3、pandas、seaborn,所有數字皆為實際執行結果。

重點整理與下一步

  • EDA 的順序:認識資料 → 驗證與清理 → 找模式與關聯 → 產生新特徵與假設。
  • 缺失值、離群值、型態錯誤,是任何真實資料都會遇到的三個問題。
  • 「異常」要先判斷是真的極端值,還是資料裡混進了不該有的東西(例如這個案例的取消單、會計科目)。
  • 下一篇:資料視覺化(Seaborn)
#Python#EDA#Pandas#數據分析
← 回到全部文章