【问题标题】:split column and get last element spark dataset拆分列并获取最后一个元素火花数据集
【发布时间】:2022-01-12 20:44:47
【问题描述】:

我写了以下代码:

def extractGenderFromName(ds: Dataset[Toto])
                          (implicit sparkSession: SparkSession): Dataset[Toto] = {
    if (ds("gender") == null)
      ds.withColumn("gender", split(col(identity), "/")(1))
}

这里我想得到 col identity 的最后一部分,我放了1 但它可以是23。如何动态取colidentity的最后一部分?

【问题讨论】:

标签: dataframe scala apache-spark apache-spark-sql apache-spark-dataset


【解决方案1】:

使用带有负索引-1element_at 函数作为数组列的最后一个元素。另外,您需要使用when 表达式来检查gender 列是否为空,而不是Scala if 语句:

ds.withColumn(
  "gender",
  when(
    col("gender").isNull, 
    element_at(split(col("identity"), "/"), -1)
  ).otherwise(col("gender"))
)

请注意,您实际上可以使用substring_index 函数,而不必像这样拆分identity 列:

substring_index(col("identity"), "/", -1)

【讨论】:

    猜你喜欢
    • 2021-02-04
    • 2016-09-20
    • 2013-01-02
    • 1970-01-01
    • 2018-12-26
    • 2010-10-13
    • 2020-08-25
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多