0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Databricksで利用できる組み込み関数

0
Posted at

Databricks(PySpark)で利用できる組み込み関数は、pyspark.sql.functions モジュールに数百種類用意されています。これらはすべて、Sparkのエンジン内で最適化して実行されます。主要なものをカテゴリー別に整理して紹介します。

数値計算・数学関数

基本的な四則演算に加え、統計的な計算を行う関数です。

関数 説明 使用例
round 指定した桁数で四捨五入 F.round(F.col(""price""), 2)
abs 絶対値を取得 F.abs(F.col(""diff""))
sqrt 平方根を取得 F.sqrt(F.col(""area""))
exp / log 指数関数 / 自然対数 F.log(F.col(""value""))

文字列操作関数

テキストデータの加工、抽出、クリーニングに使用します。

関数 説明 使用例
concat 複数の列を結合 F.concat(F.col(""first""), F.lit("" ""), F.col(""last""))
substring 文字列の一部を抽出 F.substring(F.col(""code""), 1, 3)
regexp_replace 正規表現による置換 F.regexp_replace(F.col(""phone""), r""\D"", """")
lower / upper 小文字化 / 大文字化 F.lower(F.col(""name""))
split 指定文字で分割し配列化 F.split(F.col(""address""), "" "")

3. 日付・時刻関数

日付の計算やフォーマット変換に使用します。Pandasの dt アクセサよりも高速です。

関数 説明 使用例
current_date 現在の日付を取得 F.current_date()
date_add 日付に日数を加算 F.date_add(F.col(""order_date""), 7)
datediff 2つの日付の差分 F.datediff(F.col(""end""), F.col(""start""))
year / month / day 年・月・日を抽出 F.month(F.col(""timestamp""))
to_date 文字列を日付型に変換 F.to_date(F.col(""str_col""), ""yyyyMMdd"")

4. 条件分岐・Null処理

Pythonの if-else や fillna に相当します。

関数 説明 使用例
when / otherwise 条件分岐(CASE文) F.when(cond, val1).otherwise(val2)
coalesce 最初の非NULL値を返す F.coalesce(F.col(""mobile""), F.col(""home""))
isNotNull NULLでないか判定 F.col(""email"").isNotNull()

5. 集計関数 (Aggregation)

groupBy と組み合わせて使用します。

関数 説明 使用例
sum / avg 合計 / 平均 F.avg(""salary"")
count / countDistinct 件数 / ユニーク件数 F.countDistinct(""user_id"")
collect_list 値をリストにまとめる F.collect_list(""item_id"")
approx_count_distinct 近似ユニーク数(超巨大データ用) F.approx_count_distinct(""id"")

6. 配列 (Array)・構造体 (Struct) 操作

複雑なネストデータを扱う関数です。

関数 説明 使用例
explode 配列を縦持ち(行)に展開 F.explode(F.col(""tags""))
array_contains 配列に特定値が含まれるか F.array_contains(F.col(""roles""), ""admin"")
struct 複数の列を1つの構造体にまとめる F.struct(""lat"", ""lon"")

実装のヒント:関数のインポート
これらを使うときは、慣習として以下のように F という名前でインポートします。

Python
from pyspark.sql import functions as F

# 例:日付を加工して、条件でラベルを付ける
df_final = df.withColumn("formatted_date", F.to_date("raw_date")) \
             .withColumn("is_weekend", F.dayofweek("formatted_date").isin([1, 7]))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?