【问题标题】:spark data frame operation row and column level useing scala使用scala火花数据帧操作行和列级别
【发布时间】:2019-03-24 00:59:54
【问题描述】:

原始数据框
0.2 0.3

+------+------------- -+
|  name| country |
+------+---------------+
|Raju  |UAS         |
|Ram  |Pak.         |
|null    |China      |
|null    |null          |
+------+--------------+

  I Need  this 
+------+--------------+
|Nwet|wet Con |
+------+--------------+
|0.2   | 0.3           |
|0.2   | 0.3           |
|0.0   | 0.3.          |
|0.0   | 0.0           |
+------+--------------+

我想创建一个 Udf 。两列
这将适用于 Name Column 它检查它是否不为 null 然后它返回 0.2 返回 0.0 。 并且相同的 Udf 适用于国家列检查它是否返回 0.0 。不为 null 则返回 0.3

【问题讨论】:

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


【解决方案1】:

使用apache的StringUtils:

val transcodificationName: UserDefinedFunction =
    udf { (name: String) => {
        if (StringUtils.isBlank(name)) 0.0
        else 0.2
        }
    }
val transcodificationCountry: UserDefinedFunction =
    udf { (country: String) => {
        if (StringUtils.isBlank(country)) 0.0
        else 0.3
        }
    }

dataframe
    .withColumn("Nwet", transcodificationName(col("name"))).cast(DoubleType)
    .withColumn("wetCon", transcodificationCountry(col("country"))).cast(DoubleType)
    .select("Nwet", "wetcon")

编辑:

val transcodificationColumns: UserDefinedFunction =
        udf { (input: String, columnName:String) => {
                if (StringUtils.isBlank(country)) 0.0
                else if(columnName.equals("name")) 0.2
                else if(columnName.equals("country") 0.3
                else 0.0
            }
        }


    dataframe
        .withColumn("Nwet", transcodificationColumns(col("name"), "name")).cast(DoubleType)
        .withColumn("wetCon", transcodificationColumns(col("country")), "country").cast(DoubleType)
        .select("Nwet", "wetcon")

【讨论】:

  • 我需要一个 udf 用于两列
  • 不可能,因为一个 udf 只能输出一列。另一种方法是返回一个 arrayType,但不是你的情况,因为它总是 1 列
  • 你想为每一列使用一个 udf 吗?在这种情况下,我编辑了帖子
猜你喜欢
  • 2016-05-01
  • 2020-01-21
  • 2017-05-24
  • 2018-10-27
  • 2016-04-29
  • 2016-12-16
  • 1970-01-01
相关资源
最近更新 更多