【问题标题】:Chain several WHEN conditions in a scalable way in PySpark在 PySpark 中以可扩展的方式链接多个 WHEN 条件
【发布时间】:2022-07-05 15:47:14
【问题描述】:

我有一个字典(变量 pats),其中包含许多 when 参数:条件和值。

from pyspark.sql import functions as F
df = spark.createDataFrame([("ė",), ("2",), ("",), ("@",)], ["col1"])

pats = {
  r"^\d$"          :"digit",
  r"^\p{L}$"       :"letter",
  r"^[\p{P}\p{S}]$":"spec_char",
  r"^$"            :"empty"
}

whens = (
    F.when(F.col("col1").rlike(list(pats.keys())[0]), pats[list(pats.keys())[0]])
     .when(F.col("col1").rlike(list(pats.keys())[1]), pats[list(pats.keys())[1]])
     .when(F.col("col1").rlike(list(pats.keys())[2]), pats[list(pats.keys())[2]])
     .when(F.col("col1").rlike(list(pats.keys())[3]), pats[list(pats.keys())[3]])
     .otherwise(F.col("col1"))
)
df = df.withColumn("col2", whens)

df.show()
# +----+---------+
# |col1|     col2|
# +----+---------+
# |   ė|   letter|
# |   2|    digit|
# |    |    empty|
# |   @|spec_char|
# +----+---------+

我正在寻找一种可扩展的方式来链接所有when 条件,因此我不需要为每个键写一行。

【问题讨论】:

    标签: apache-spark dictionary pyspark conditional-statements method-chaining


    【解决方案1】:

    reduce可以用。

    from functools import reduce
    
    whens = reduce(
        lambda acc, p: acc.when(F.col("col1").rlike(p), pats[p]),
        list(pats.keys()),
        F.when(F.lit(False), "1")
    ).otherwise(F.col("col1"))
    

    完整代码:

    from pyspark.sql import functions as F
    from functools import reduce
    df = spark.createDataFrame([("ė",), ("2",), ("",), ("@",)], ["col1"])
    
    pats = {
      r"^\d$"          :"digit",
      r"^\p{L}$"       :"letter",
      r"^[\p{P}\p{S}]$":"spec_char",
      r"^$"            :"empty"
    }
    
    whens = reduce(
        lambda acc, p: acc.when(F.col("col1").rlike(p), pats[p]),
        pats.keys(),
        F.when(F.lit(False), "1")
    ).otherwise(F.col("col1"))
    
    df = df.withColumn("col2", whens)
    
    df.show()
    # +----+---------+
    # |col1|     col2|
    # +----+---------+
    # |   ė|   letter|
    # |   2|    digit|
    # |    |    empty|
    # |   @|spec_char|
    # +----+---------+
    

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 2013-11-02
      相关资源
      最近更新 更多