scala – 在DataFrame上定义自定义方法的最佳方法是什么?
发布时间:2020-12-16 09:25:26 所属栏目:安全 来源:网络整理
导读:我需要在DataFrame上定义自定义方法.有什么更好的方法呢?解决方案应该是可扩展的,因为我打算定义大量的自定义方法. 我目前的方法是使用DataFrame作为参数创建一个类(比如MyClass),在其中定义我的自定义方法(比如customMethod)并定义一个将DataFrame转换为My
我需要在DataFrame上定义自定义方法.有什么更好的方法呢?解决方案应该是可扩展的,因为我打算定义大量的自定义方法.
我目前的方法是使用DataFrame作为参数创建一个类(比如MyClass),在其中定义我的自定义方法(比如customMethod)并定义一个将DataFrame转换为MyClass的隐式方法. implicit def dataFrametoMyClass(df: DataFrame): MyClass = new MyClass(df) 所以我可以打电话: dataFrame.customMethod() 这是正确的方法吗?公开征求意见. 解决方法
你的方式是要走的路(见[1]).虽然我解决了一点不同,但方法仍然类似:
可能性1 Implicits object ExtraDataFrameOperations { object implicits { implicit def dFWithExtraOperations(df: DataFrame) = DFWithExtraOperations(df) } } case class DFWithExtraOperations(df: DataFrame) { def customMethod(param: String) : DataFrame = { // do something fancy with the df // or delegate to some implementation // // here,just as an illustrating example: do a select df.select( df(param) ) } } 用法 要在DataFrame上使用新的customMethod方法: import ExtraDataFrameOperations.implicits._ val df = ... val otherDF = df.customMethod("hello") 可能性2 您也可以使用隐式类,而不是使用隐式方法(参见上文): 隐含的类 object ExtraDataFrameOperations { implicit class DFWithExtraOperations(df : DataFrame) { def customMethod(param: String) : DataFrame = { // do something fancy with the df // or delegate to some implementation // // here,just as an illustrating example: do a select df.select( df(param) ) } } } 用法 import ExtraDataFrameOperations._ val df = ... val otherDF = df.customMethod("hello") 备注 如果要阻止其他导入,请将对象ExtraDataFrameOperations转换为包对象,并将其存储在包中名为package.scala的文件中. 官方文件/参考资料 [1] M. Odersky的原创博客“Pimp my library”可在http://www.artima.com/weblogs/viewpost.jsp?thread=179766获得 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |