進階 DataFrame 操作

PySpark 入門

Ben Schmidt

Data Engineer

PySpark 的 Join

  • 依共同欄位合併兩個以上 DataFrame 的列
  • 連接類型:inner、left、right、outer,類似 SQL

  • 語法:DataFrame1.join(DataFrame2, on="column", how="join_type")

# 以 id 欄位做 inner join
df_joined = df1.join(df2, on="id", how="inner")

# 連接不同欄位名稱 df_joined = df1.join(df2, df1.Id == df2.Name, "inner")
PySpark 入門

Union 操作

  • 合併兩個具相同結構的 DataFrame 的列

  • 語法:DataFrame1.union(DataFrame2)

# 合併兩個結構相同的 DataFrame
df_union = df1.union(df2)
PySpark 入門

操作 Arrays 與 Maps

Arrays: 適合在欄位中存放清單,語法:ArrayType(StringType(),False)

from pyspark.sql.functions import array, struct, lit

# 建立陣列欄位
df = df.withColumn("scores", array(lit(85), lit(90), lit(78)))

Maps: 鍵值配對,適合類似字典的資料,MapType(StringType(),StringType())

from pyspark.sql.types import StructField, StructType, StringType, MapType

schema = StructType([
    StructField('name', StringType(), True),
    StructField('properties', MapType(StringType(), StringType()), True)
])
PySpark 入門

操作 Structs

  • Structs:在列內建立巢狀結構。語法:StructType(Structfield, Datatype())
# 建立 struct 欄位
df = df.withColumn("name_struct", struct("first_name", "last_name"))

# 建立 struct 欄位 df = df.withColumn("name_struct", struct("first_name", "last_name"))
PySpark 入門

一起來練習吧!

PySpark 入門

Preparing Video For Download...