当前位置: 首页 > news >正文

【Spark】用udf和withColumn在dafaframe中创建新列

udf使用

import org.apache.spark.sql.functions.udf
udf接收一个函数(func)作为参数,返回一个UserDefinedFunction。
UserDefinedFunction接收列(Column)作为参数,并返回Column.
func可以接收普通类型参数,并返回普通类型结果。
udf会自动把Column入参转化成对应func的入参,并将func返回的结果转化成Column类型。、

注意由于udf限制。func最多接收10个参数

import org.apache.spark.sql.functions._
//一个或多个参数
val UDF0= udf{(c1:String,c2:Int,...,)=> 函数体
}df.withColumn("new",UDF0(col("old1"),col("old2")...))//整行输入
val UDF1= udf{(row: Row) => 处理Row类型的函数体,最好返回常规类型
}val columns = df.columnsdf.withColumn("new",UDF1(struct(columns.map(x=>col(x)): _*))// 注册到sql中使用df.createOrReplaceTempView("tempview")spark.udf.register("UDF0", UDF0)spark.sql("select *, UDF0(struct(`old1`, `old2`, `...`)) as new from tempview").show(100)

struct函数说明:

def struct(colName: String, colNames: String*): Column
// Creates a new struct column that composes multiple input columns.
def struct(cols: Column*): Column
// Creates a new struct column. If the input column is a column in a DataFrame, or a derived column expression that is named (i.e. aliased), its name would be retained as the StructField's name, otherwise, the newly generated StructField's name would be auto generated as col with a suffix index + 1, i.e. col1, col2, col3, ...

参考

create-new-column-with-function-in-spark-dataframe

【官方】udf使用
【官方】udf接口
Spark SQL UDF (User Defined Functions)

http://www.lryc.cn/news/168178.html

相关文章:

  • AIGC 设计能替代真正的设计师设计吗?
  • 【1++的C++进阶】之emplace详解
  • React入门
  • 第三方登录以及验证
  • MS SQL Server问题汇总
  • 在线海报图片设计器、图片编辑器源码/仿照稿定设计源码
  • KMP算法(C++)
  • C++的异常类型与多级catch匹配
  • 查询IP地址可得到哪些信息
  • 考研算法47天:01背包
  • Docker实战技巧(一):Kubernetes基础操作实战
  • android java读写yaml文件
  • 科学计算器网站Desmos网站
  • 结构体-时间的计算
  • pt24django教程
  • Golang开发-new关键字
  • 遗传算法与粒子群算法的Python实现
  • 无涯教程-JavaScript - ASINH函数
  • ActiveMQ面试题(一)
  • node:glob语法以及常用的文件查找库glob、fast-glob
  • 饲料添加剂 微生物 屎肠球菌
  • 二叉搜索树经典笔试题【力扣、牛客】
  • docker系列(1) - docker环境篇
  • web安全漏洞-SQL注入攻击实验
  • 直接插入排序(C++实现)
  • 【k8s】Pod 的钩子
  • MCU软核 3. Xilinx Artix7上运行cortex-m3软核
  • 基于SpringbootShiro实现的CAS单点登录
  • SocketTool V4.0 使用说明
  • Jenkins结合allure生成测试报告