2016-07-26 127 views
2

Spark-Scala環境中的withColumn函數存在一些問題。 我想在我的數據框添加新列這樣的:Spark,在Scala中添加具有相同值的新列

+---+----+---+ 
| A| B| C| 
+---+----+---+ 
| 4|blah| 2| 
| 2| | 3| 
| 56| foo| 3| 
|100|null| 5| 
+---+----+---+ 

變成了:

+---+----+---+-----+ 
| A| B| C| D | 
+---+----+---+-----+ 
| 4|blah| 2| 750| 
| 2| | 3| 750| 
| 56| foo| 3| 750| 
|100|null| 5| 750| 
+---+----+---+-----+ 

在一個值的列d重複N次在我的數據幀的每一行。

的代碼是這樣的:

var totVehicles : Double = df_totVehicles(0).getDouble(0); //return 750 

變量totVehicles返回正確的值,它的作品!

第二數據幀必須計算2個字段(id_zipcode,n_vehicles),並添加第三列(具有相同的值-750):

var df_nVehicles = 
df_carPark.filter(
     substring($"id_time",1,4) < 2013 
    ).groupBy(
     $"id_zipcode" 
    ).agg(
     sum($"n_vehicles") as 'n_vehicles 
    ).select(
     $"id_zipcode" as 'id_zipcode, 
     'n_vehicles 
    ).orderBy(
     'id_zipcode, 
     'n_vehicles 
    ); 

最後,我與withColumn函數添加新列:

var df_nVehicles2 = df_nVehicles.withColumn(totVehicles, df_nVehicles("n_vehicles") + df_nVehicles("id_zipcode")) 

但是星火返回我這個錯誤:

error: value withColumn is not a member of Unit 
     var df_nVehicles2 = df_nVehicles.withColumn(totVehicles, df_nVehicles("n_vehicles") + df_nVehicles("id_zipcode")) 

你可以幫我嗎? 非常感謝!

回答

10

​​3210功能是用於將文字值作爲列

import org.apache.spark.sql.functions._ 
df.withColumn("D", lit(750)) 
相關問題