高级 DataFrame 操作

PySpark 入门

Ben Schmidt

Data Engineer

PySpark 中的连接(Join)

  • 基于公共列合并两个或多个 DataFrame 的行
  • 连接类型:inner、left、right、outer(类似 SQL)

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

# 在 id 列上进行内连接
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 入门

处理 Array 和 Map

数组(Array): 用于在列中存放列表,语法:ArrayType(StringType(),False)`

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

# 创建数组列
df = df.withColumn("scores", array(lit(85), lit(90), lit(78)))

映射(Map): 键值对,适合字典式数据,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 入门

处理 Struct

  • Struct:在行内创建嵌套结构;语法: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...