scala 使用withColumn方法

scala – 使用withColumn将两列添加到现有DataFrame
现在我想再向现有的DataFrame添加两列.

目前我正在使用DataFrame中的withColumn方法执行此操作.
withColumn()方法:

 withColumn(colName, col)[source]

    Returns a new DataFrame by adding a column or replacing the existing column that has the same name.

    The column expression must be an expression over this DataFrame; attempting to add a column from some other dataframe will raise an error.

    Parameters

            colName – string, name of the new column.

            col – a Column expression for the new column.

    >>> df.withColumn('age2', df.age + 2).collect()
    [Row(age=2, name='Alice', age2=4), Row(age=5, name='Bob', age2=7)]


例如:

df.withColumn("newColumn1", udf(col("somecolumn")))
  .withColumn("newColumn2", udf(col("somecolumn")))

这种方法需要两次调用AFAIk(每个新列一次).但是如果你的udf计算量很大,你可以避免在将“复杂”结果存储到临时列中然后“解压缩”结果时将其调用两次

使用案例类或元组作为udf的结果

编辑:

使用UDF返回元组,解压缩将如下所示:

val newDf = df
    .withColumn("udfResult",myUDf(col("name")))
    .withColumn("lowercaseColumn", col("udfResult._1"))
    .withColumn("uppercaseColumn", col("udfResult._2"))
    .drop("udfResult")
  

文章参考:https://codeday.me/bug/20180824/228440.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值