PySpark 入門
Benjamin Schmidt
Data Engineer
spark.read.csv("path/to/file.csv")
spark.read.json("path/to/file.json")
spark.read.parquet("path/to/file.parquet")
Spark 可用 inferSchema=True 從資料推斷綱要
也可手動定義綱要以更精準控制——適合固定結構

IntegerType:整數1、3478、-18904569223347758063.14159"This is an example of a string."# 匯入所需型別類別
from pyspark.sql.types import (StructType,
StructField, IntegerType,
StringType, ArrayType)
# 建立綱要(schema)
schema = StructType([
StructField("id", IntegerType(), True),
StructField("name", StringType(), True),
StructField("scores", ArrayType(IntegerType()), True)
])
# 套用綱要
df = spark.createDataFrame(data, schema=schema)
.select() 選取特定欄位.filter() 或 .where() 依條件篩選列.sort() 依多欄位排序# 只選取並顯示 name 與 age 欄位
df.select("name", "age").show()
# 篩選 age > 30
df.filter(df["age"] > 30).show()
# 使用 where 篩選特定值
df.where(df["age"] == 30).show()
# 使用 sort 依年齡排序
df.sort("age", ascending=False).show()
.sort() 或 .orderBy() 排序na.drop() 移除含 null 的列# 以 age 欄位排序
df.sort("age", ascending=False).show()
# 移除遺漏值
df.na.drop().show()
spark.read_json():從 JSON 載入資料spark.read.schema():明確定義綱要.na.drop():刪除含遺漏值的列.select()、.filter()、.sort()、.orderBy():基本資料操作PySpark 入門