メインコンテンツまでスキップ

存在する( DataFrame )

EXISTSサブクエリの場合はColumnオブジェクトを返します。

構文

exists()

戻り値

Column: EXISTS サブクエリを表すColumnオブジェクト。

注意

existsメソッドは、サブクエリ内の関連レコードの存在を確認するブール列を作成する方法を提供します。 DataFrame内でこのメソッドを適用すると、関連するデータセットに一致するレコードが存在するかどうかに基づいて行をフィルタリングできます。結果のColumnオブジェクトは、フィルター条件で直接使用することも、コンピュート列として使用することもできます。

Python
data_customers = [
(101, "Alice", "USA"), (102, "Bob", "Canada"), (103, "Charlie", "USA"),
(104, "David", "Australia")
]
data_orders = [
(1, 101, "2023-01-15", 250), (2, 102, "2023-01-20", 300),
(3, 103, "2023-01-25", 400), (4, 101, "2023-02-05", 150)
]
customers = spark.createDataFrame(
data_customers, ["customer_id", "customer_name", "country"])
orders = spark.createDataFrame(
data_orders, ["order_id", "customer_id", "order_date", "total_amount"])

from pyspark.sql import functions as sf
customers.alias("c").where(
orders.alias("o").where(
sf.col("o.customer_id") == sf.col("c.customer_id").outer()
).exists()
).orderBy("customer_id").show()
# +-----------+-------------+-------+
# |customer_id|customer_name|country|
# +-----------+-------------+-------+
# | 101| Alice| USA|
# | 102| Bob| Canada|
# | 103| Charlie| USA|
# +-----------+-------------+-------+

customers.alias("c").where(
~orders.alias("o").where(
sf.col("o.customer_id") == sf.col("c.customer_id").outer()
).exists()
).orderBy("customer_id").show()
# +-----------+-------------+---------+
# |customer_id|customer_name| country|
# +-----------+-------------+---------+
# | 104| David|Australia|
# +-----------+-------------+---------+
このページの見出し