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

エントリからのマップ

キーと値のペアのエントリ (2 つのフィールドを持つ構造体) の配列をマップに変換します。各エントリの最初のフィールドはキーとして使用され、2 番目のフィールドは結果のマップ列の値として使用されます。

構文

Python
from pyspark.sql import functions as sf

sf.map_from_entries(col)

パラメーター

パラメーター

Type

説明

col

pyspark.sql.Column または文字列

列または式の名前

戻り値

pyspark.sql.Column: 指定されたエントリの配列から作成されたマップ。

例1 : map_from_entriesの基本的な使い方

Python
from pyspark.sql import functions as sf
df = spark.sql("SELECT array(struct(1, 'a'), struct(2, 'b')) as data")
df.select(sf.map_from_entries(df.data)).show()
Output
+----------------------+
|map_from_entries(data)|
+----------------------+
| {1 -> a, 2 -> b}|
+----------------------+

例2 : null値を持つmap_from_entries

Python
from pyspark.sql import functions as sf
df = spark.sql("SELECT array(struct(1, null), struct(2, 'b')) as data")
df.select(sf.map_from_entries(df.data)).show()
Output
+----------------------+
|map_from_entries(data)|
+----------------------+
| {1 -> NULL, 2 -> b}|
+----------------------+

例3 : DataFrameを使用したmap_from_entries

Python
from pyspark.sql import Row, functions as sf
df = spark.createDataFrame([([Row(1, "a"), Row(2, "b")],), ([Row(3, "c")],)], ['data'])
df.select(sf.map_from_entries(df.data)).show()
Output
+----------------------+
|map_from_entries(data)|
+----------------------+
| {1 -> a, 2 -> b}|
| {3 -> c}|
+----------------------+

例4 : 空の配列を持つ map_from_entries

Python
from pyspark.sql import functions as sf
from pyspark.sql.types import ArrayType, StringType, IntegerType, StructType, StructField
schema = StructType([
StructField("data", ArrayType(
StructType([
StructField("key", IntegerType()),
StructField("value", StringType())
])
), True)
])
df = spark.createDataFrame([([],)], schema=schema)
df.select(sf.map_from_entries(df.data)).show()
Output
+----------------------+
|map_from_entries(data)|
+----------------------+
| {}|
+----------------------+