我在Scala中的DataFrame
中存在将值置换的问题。我最初的DataFrame
看起来是这样的:Spark:将UDF应用于数据框根据DF中的值生成新列
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
| A| X| 6|null|
| B| Z|null| 5|
| C| Y| 4|null|
+----+----+----+----+
col1
和col2
是String
类型和col3
和col4
是Int
。
而结果应该是这样的:
+----+----+----+----+------+------+------+
|col1|col2|col3|col4|AXcol3|BZcol4|CYcol4|
+----+----+----+----+------+------+------+
| A| X| 6|null| 6| null| null|
| B| Z|null| 5| null| 5| null|
| C| Y| 4| 4| null| null| 4|
+----+----+----+----+------+------+------+
这意味着三个新列后应col1
,col2
并提取值的列被命名。提取的值来自列col2
,col3
或col5
,取决于哪个值不是null
。
那么如何实现呢?我首先想到的一个UDF
这样的:
def myFunc (col1:String, col2:String, col3:Long, col4:Long) : (newColumn:String, rowValue:Long) = {
if col3 == null{
val rowValue=col4;
val newColumn=col1+col2+"col4";
} else{
val rowValue=col3;
val newColumn=col1+col2+"col3";
}
return (newColumn, rowValue);
}
val udfMyFunc = udf(myFunc _) //needed to treat it as partially applied function
但我怎么能以正确的方式把它从数据帧?
当然,上面的所有代码都是垃圾,可能有更好的方法。因为我只是玩杂耍的第一个代码片段让我知道...比较Int
值到null
已不起作用。
任何帮助表示赞赏!谢谢!
[Apache Spark - 将UDF的结果分配给多个数据帧列]可能的重复(http://stackoverflow.com/questions/35322764/apache-spark-assign-the-result-of-udf-to-多个数据帧列) – jwvh