資料清理與品質檢查

在 Databricks 使用 Spark SQL 進行資料轉換

Disha Mukherjee

Lead Data Engineer

真實資料的三大問題

recraft: half: 一堆散落的文件與檔案,含錯誤與空缺,透明背景獨立

 

  • 關鍵欄位的「遺漏值」
  • 重複匯入造成的「重複列」
  • 「邏輯無效」的紀錄
在 Databricks 使用 Spark SQL 進行資料轉換

為何要明確定義綱要(schema)?

recraft: half: 一位困惑的科學家,試算表列上方漂浮問號,透明背景獨立

 

  • Spark 可能誤判欄位型別
  • 數值欄可能被推斷成字串
  • StructType 明確定義型別,每次執行都一致
在 Databricks 使用 Spark SQL 進行資料轉換

匯入模組

from pyspark.sql.types import (
    StructType, StructField,
    StringType, DoubleType, IntegerType, TimestampType
)

from pyspark.sql import functions as F
在 Databricks 使用 Spark SQL 進行資料轉換

定義綱要(schema)

schema = StructType([
    StructField("ID",                 IntegerType(),   True),
    StructField("Date",               TimestampType(), True),
    StructField("Transaction_Amount", DoubleType(),    True),
    StructField("Transaction_Status", StringType(),    True),
    # ... 6 more fields
])

df = (spark.read.format("csv") .option("header", "true") .schema(schema) .load("/Volumes/.../transactions.csv"))
df.printSchema()
 |-- ID: integer (nullable = true)
 |-- Date: timestamp (nullable = true)
 |-- Transaction_Amount: double (nullable = true)
 |-- Transaction_Status: string (nullable = true)
 ...
在 Databricks 使用 Spark SQL 進行資料轉換

找出遺漏值

null_counts = df.select([
    F.sum(F.col(c).isNull().cast("int")).alias(c)
    for c in df.columns
])

null_counts.show()
+-----------+------------------+--------+--------+
|Customer_ID|Transaction_Amount|Category|Location|
+-----------+------------------+--------+--------+
|30         |50                |40      |30      |
+-----------+------------------+--------+--------+
在 Databricks 使用 Spark SQL 進行資料轉換

刪除與填補遺漏值

df_no_nulls = df.na.drop(subset=["Customer_ID"])

df_filled = df_no_nulls.na.fill({ "Transaction_Amount": 0.0, "Category": "Unknown", "Location": "Unknown" })
print(f"Before: {df.count()}") print(f"After: {df_filled.count()}")
Before: 100,150
After:  100,120
在 Databricks 使用 Spark SQL 進行資料轉換

處理重複值

total = df_filled.count()
distinct = df_filled.distinct().count()

print(f"Duplicates: {total - distinct}")
Duplicates: 149
在 Databricks 使用 Spark SQL 進行資料轉換

處理重複值

df_deduped = df_filled.dropDuplicates(
    subset=["Customer_ID", "Date", "Transaction_Amount"]
)

print(f"Rows after dedup: {df_deduped.count()}")
Rows after dedup: 99,971
在 Databricks 使用 Spark SQL 進行資料轉換

過濾無效紀錄

df_valid = df_deduped.filter(F.col("Transaction_Amount") > 0)

df_valid = df_valid.filter( F.col("Transaction_Status") == "Completed" )
print(f"Valid transactions: {df_valid.count()}")
Valid transactions: 33,223
在 Databricks 使用 Spark SQL 進行資料轉換

建立衍生欄位

df_enriched = df_valid.withColumn("Revenue_Band",
    F.when(F.col("Transaction_Amount") >= 50000, "High")
     .when(F.col("Transaction_Amount") >= 10000, "Medium")

.otherwise("Low"))
df_enriched.select("Customer_ID", "Transaction_Amount", "Revenue_Band").show(3)
+-----------+------------------+------------+
|Customer_ID|Transaction_Amount|Revenue_Band|
+-----------+------------------+------------+
|CUST003    |5752.36           |Low         |
|CUST009    |28959.12          |Medium      |
|CUST010    |72098.18          |High        |
+-----------+------------------+------------+
在 Databricks 使用 Spark SQL 進行資料轉換

資料品質檢查

total_rows = df_enriched.count()
distinct_rows = df_enriched.distinct().count()

null_rate = ( df_enriched.filter(F.col("Customer_ID").isNull()) .count() / total_rows * 100 )
print(f"Total rows: {total_rows}") print(f"Duplicates: {total_rows - distinct_rows}") print(f"Null rate: {null_rate:.2f}%")
Total rows:   33,223
Duplicates:   0
Null rate:    0.00%
在 Databricks 使用 Spark SQL 進行資料轉換

一起來練習吧!

在 Databricks 使用 Spark SQL 進行資料轉換

Preparing Video For Download...