假設我有一個如下的資料框:
| id |col
| 1 | "A,B,C"
| 2 | "D,C"
| 3 | "B,C,A"
| 4 | None
字典是:
d = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
輸出資料幀必須是:
| id |col
| 1 | "A"
| 2 | "C"
| 3 | "A"
| 4 | None
uj5u.com熱心網友回復:
Higher Order Functions - Transform可用于col根據字典關聯元素的排名,然后排序以獲取排名最低的元素。
from pyspark.sql import functions as F
from itertools import chain
data = [(1, "A,B,C",),
(2, "D,C",),
(3, "B,C,A",),
(4, None,), ]
df = spark.createDataFrame(data, ("id", "col", ))
d = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
mapper = F.create_map([F.lit(c) for c in chain.from_iterable(d.items())])
"""
Mapper has the value Column<'map(A, 1, B, 2, C, 3, D, 4)'>
"""
(df.withColumn("col", F.split(F.col("col"), ",")) # Split string to create an array
.withColumn("mapper", mapper) # Add mapping columing to the dataframe
.withColumn("col", F.expr("transform(col, x -> struct(mapper[x] as rank, x as col))")) # Iterate over array and look up rank from mapper
.withColumn("col", F.array_min(F.col("col")).col) # array_min find minimum value based on the first struct field
).select("id", "col").show()
"""
--- ----
| id| col|
--- ----
| 1| A|
| 2| C|
| 3| A|
| 4|null|
--- ----
"""
uj5u.com熱心網友回復:
這是另一個將結構排序為@Nithish 答案但使用arrays_zipand 的解決方案array_min:
- 從字典創建權重陣列(按鍵排序)
- 使用拆分
col排序的結果壓縮權重陣列 - 獲取壓縮結構陣列的陣列最小值
import pyspark.sql.functions as F
df = spark.createDataFrame([(1, "A,B,C"), (2, "D,C"), (3, "B,C,A"), (4, None)], ["id", "col"])
d = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
result = df.withColumn(
"col",
F.array_min(
F.arrays_zip(
F.array(*[F.lit(d[x]) for x in sorted(d)]),
F.array_sort(F.split("col", ","))
)
)["1"]
)
result.show()
# --- ----
#| id| col|
# --- ----
#| 1| A|
#| 2| C|
#| 3| A|
#| 4|null|
# --- ----
uj5u.com熱心網友回復:
我假設您想根據字典中給出的值對字母進行排序d。
然后,您可以執行以下操作:
from pyspark.sql import Row
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
import pyspark.sql.types as T
spark = SparkSession.builder.master("local").appName("sort_column_test").getOrCreate()
df = spark.createDataFrame(data=(Row(1, "A,B,C",),
Row(2, "D,C",),
Row(3, "B,C,A",),
Row(4, None)),
schema="id:int, col:string")
d = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
# Define a sort UDF that sorts the array according to the dictionary 'd', also handles None arrays
sort_udf = F.udf(lambda array: sorted(array,
key=lambda x: d[x]) if array is not None else None,
T.ArrayType(T.StringType()))
df = df.withColumn("col", sort_udf(F.split(F.col("col"), ",")).getItem(0))
df.show()
"""
--- ----
| id| col|
--- ----
| 1| A|
| 2| C|
| 3| A|
| 4|null|
--- ----
"""
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/398847.html
