我需要在 DataFrame 上定义自定义方法。什么是更好的方法?该解决方案应该是可扩展的,因为我打算定义大量的自定义方法。
我目前的方法是用 MyClass
创建一个类(比如 DataFrame
)作为参数,在其中定义我的自定义方法(比如 customMethod
)并定义一个隐式方法来转换 DataFrame
至 MyClass
.
implicit def dataFrametoMyClass(df: DataFrame): MyClass = new MyClass(df)
因此我可以调用:
dataFrame.customMethod()
这是正确的方法吗?打开建议。
最佳答案
你的方式就是要走的路(见[1])。尽管我解决的方法略有不同,但方法保持相似:
可能性 1
隐含
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) )
}
}
用法
使用新
customMethod
DataFrame
上的方法:import ExtraDataFrameOperations.implicits._
val df = ...
val otherDF = df.customMethod("hello")
可能性2
而不是使用
implicit method
(见上文),你也可以使用 implicit class
:隐式类
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")
备注
如果您想阻止额外的
import
,转object
ExtraDataFrameOperations
成package object
并将其存储在名为 package.scala
的文件中在您的包裹内。官方文档/引用
[1] M. Odersky 的原始博客“Pimp my library”位于 http://www.artima.com/weblogs/viewpost.jsp?thread=179766
关于scala - 在 DataFrame 上定义自定义方法的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32585670/