将标题和列添加到dataframe spark

时间:2017-03-31 13:08:22

标签: scala apache-spark-sql spark-csv

大家好我有一个数据框,我想在其中添加标题和第一列 这里手动是数据框

import org.apache.spark.sql.SparkSession 

val spark = SparkSession.builder.master("local").appName("my-spark-app").getOrCreate()
val df = spark.read.option("header",true).option("inferSchema",true).csv("C:\\gg.csv").cache()

数据框的内容

12,13,14
11,10,5
3,2,45

预期输出

define,col1,col2,col3
c1,12,13,14
c2,11,10,5
c3,3,2,45

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

您想要做的是:

df.withColumn("columnName", column) //here "columnName" should be "define" for you

现在您只需要创建上述列(this可能有帮助)

答案 1 :(得分:1)

这是一个取决于Spark 2.4的解决方案:

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}
import org.apache.spark.sql.Row

//First off the dataframe needs to be loaded with the expected schema

val spark = SparkSession.builder().appName().getOrCreate()

val schema = new StructType()
              .add("col1",IntegerType,true)
              .add("col2",IntegerType,true)
              .add("col3",IntegerType,true)

val df = spark.read.format("csv").schema(schema).load("C:\\gg.csv").cache()

val rddWithId = df.rdd.zipWithIndex

// Prepend "define" column of type Long
val newSchema = StructType(Array(StructField("define", StringType, false))         ++ df.schema.fields)

val dfZippedWithId =  spark.createDataFrame(rddWithId.map{ 
                       case (row, index) => 
                       Row.fromSeq(Array("c" + index) ++ row.toSeq)}, newSchema)
// Show results
dfZippedWithId.show

显示:

+------+----+----+----+
|define|col1|col2|col3|
+------+----+----+----+
|    c0|  12|  13|  14|
|    c1|  11|  10|   5|
|    c2|   3|   2|  45|
+------+----+----+----+

这是文档here和此example的混合。