使用 Apache Spark 進行資料清理入門

使用 PySpark 清理資料

Mike Metzger

Data Engineering Consultant

什麼是資料清理?

資料清理:為資料處理流程準備原始資料。

資料清理可能包含:

  • 重新格式化或取代文字
  • 執行計算
  • 移除雜訊或不完整資料
使用 PySpark 清理資料

為何用 Spark 做資料清理?

典型資料系統的問題:

  • 效能
  • 資料流組織

Spark 的優勢:

  • 可擴充
  • 強大的資料處理框架
使用 PySpark 清理資料

資料清理範例

原始資料:

name age (years) city
Smith, John 37 Dallas
Wilson, A. 59 Chicago
null 215

清理後資料:

last name first name age (months) state
Smith John 444 TX
Wilson A. 708 IL
使用 PySpark 清理資料

Spark 結構描述(Schema)

  • 定義 DataFrame 的格式
  • 可包含多種資料型別:
    • 字串、日期、整數、陣列
  • 匯入時可過濾雜訊資料
  • 提升讀取效能
使用 PySpark 清理資料

Spark 結構描述範例

匯入結構描述

import pyspark.sql.types
peopleSchema = StructType([
  # Define the name field
  StructField('name', StringType(), True),
  # Add the age field
  StructField('age', IntegerType(), True),
  # Add the city field
  StructField('city', StringType(), True)  
])

讀取包含資料的 CSV 檔

people_df = spark.read.format('csv').load(name='rawdata.csv', schema=peopleSchema)
使用 PySpark 清理資料

一起來練習吧!

使用 PySpark 清理資料

Preparing Video For Download...