我在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