2017-04-26 6 views
0

に基づいて、火花データフレームの列名を変更します。私はトラブルcsvファイルに基づいてデータフレームのヘッダの名前を変更しましたCSV

私は、次のデータフレームました:DF1を:

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

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

は今、私はこのようになりますcsvファイルに基づいて、列名(最初の行)を変更したいですその結果、私はデータフレーム、魔女はこのように見える:

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| 
+---+------+--------+ 
関連する問題