2017-04-26 192 views
0

我很難根據csv重命名數據幀的頭。根據csv重命名火花數據幀的列名稱

我得到了以下數據幀:DF1:

Att1 Att2  Att3 
23  m  0  
22  m  1  
42  f  0 
32  f  0  
45  m  1  

現在我想基於一個CSV文件,它看起來像這樣改變的列名(第一行):

Att1,age 
Att2,gender  
Att3,employed 
...,...  
Att99,colnameY  
Att100,colnameZ 

因此,我期望一個數據框,女巫看起來像這樣:

age gender employed 
23  m  0  
22  m  1  
42  f  0 
32  f  0  
45  m  1  

有什麼想法嗎? 謝謝你的幫助:)

回答

2
import scala.io.Source.fromFile 

// read in the names map from old names to new names 
val map = fromFile("names.csv").getLines.map(line => { 
    val fields = line.split(",") 
    (fields(0), fields(1)) 
}).toMap 
// map: scala.collection.immutable.Map[String,String] = Map(Att1 -> age, Att2 -> gender, Att3 -> employed) 

// rename columns using withColumnRenamed 
df1.columns.foldLeft(df1){ 
    case (df, col) => df.withColumnRenamed(col, map.getOrElse(col, col)) 
}.show 
+---+------+--------+ 
|age|gender|employed| 
+---+------+--------+ 
| 23|  m|  0| 
| 22|  m|  1| 
| 42|  f|  0| 
| 32|  f|  0| 
| 45|  m|  1| 
+---+------+--------+