高度なDataFrame操作

PySpark 入門

Ben Schmidt

Data Engineer

PySparkでの結合

  • 共通の列に基づいて、2つ以上のDataFrameの行を結合する
  • 結合の種類: 内部、左、右、外部。SQL {{2}} のように

  • 構文: 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 入門

和集合演算

  • 同じスキーマを持つ2つのDataFrameの行を結合します

  • 構文: DataFrame1.union(DataFrame2)

# Union of two DataFrames with identical schemas
df_union = df1.union(df2)
PySpark 入門

配列とマップの操作

配列: 列内でリストを保存するのに便利です。構文: 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)))

マップ: キーと値のペア、辞書形式のデータに便利、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 の操作

  • 構造体: 行内にネストされた構造を作成する 構文: 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...