การดำเนินการขั้นสูงกับ DataFrame

PySpark เบื้องต้น

Ben Schmidt

Data Engineer

Joins ใน PySpark

  • รวมแถวจาก DataFrame ตั้งแต่สองตัวขึ้นไปโดยอิงคอลัมน์ที่มีร่วมกัน
  • ประเภทของ join: inner, left, right และ outer เหมือนใน SQL

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

# Joining on id column using an inner join
df_joined = df1.join(df2, on="id", how="inner")

# Joining on columns with different names df_joined = df1.join(df2, df1.Id == df2.Name, "inner")
PySpark เบื้องต้น

การดำเนินการ Union

  • รวมแถวจาก DataFrame สองตัวที่มี schema เหมือนกัน

  • Syntax: DataFrame1.union(DataFrame2)

# Union of two DataFrames with identical schemas
df_union = df1.union(df2)
PySpark เบื้องต้น

การใช้งาน Arrays และ Maps

Arrays: ใช้เก็บลิสต์ภายในคอลัมน์ syntax: ArrayType(StringType(),False)`

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

# Create an array column
df = df.withColumn("scores", array(lit(85), lit(90), lit(78)))

Maps: คู่ key-value เหมาะสำหรับข้อมูลแบบ dictionary 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: สร้างโครงสร้างซ้อนภายในแถว Syntax: StructType(Structfield, Datatype())
# Create a struct column
df = df.withColumn("name_struct", struct("first_name", "last_name"))

# Create a struct column df = df.withColumn("name_struct", struct("first_name", "last_name"))
PySpark เบื้องต้น

มาฝึกกันเถอะ!

PySpark เบื้องต้น

Preparing Video For Download...