/ / Jak ustawić rzędy i kolumny w Sparku za pomocą scala [duplicate] - scala, Apache-spark, ramka danych, tekst, wiersze

Jak ustawić rzędy i kolumny w Sparku za pomocą scala [duplicate] - scala, Apache-spark, ramka danych, tekst, wiersze

Chcę z pliku tekstowego w formacie:

first line
column1;column2;column3
column1;column2;column3
last line

przekształcić go w DataFrame bez pierwszegoi ostatnia linia Mam pierwszą i ostatnią linię, ale potem zostanę tekstem w jednym wierszu i kolumnie Jak mogę uporządkować wiersze? Mam również schemat dla mojej DataFrame

var textFile = sc.textFile("*.txt")
val header = textFile.first()
val total = textFile.count()
var rows = textFile.zipWithIndex().filter(x => x._2 < total - 1).map(x => x._1).filter(x => x !=  header)

val schema = StructType(Array(
StructField("col1", IntegerType, true),
StructField("col2", StringType, true),
StructField("col3", StringType, true),
StructField("col4", StringType, true)
))

Odpowiedzi:

0 dla odpowiedzi № 1

Powinieneś wykonać następujące czynności (skomentowałeś dla jasności)

//creating schema
import org.apache.spark.sql.types._
val schema = StructType(Array(
StructField("col1", StringType, true),
StructField("col2", StringType, true),
StructField("col3", StringType, true)
))

//reading text file and finding total lines
val textFile = sc.textFile("*.txt")
val total = textFile.count()

//indexing lines for filtering the first and the last lines
import org.apache.spark.sql.Row
val rows = textFile.zipWithIndex()
.filter(x => x._2 != 0 && x._2 < total - 1)
.map(x => Row.fromSeq(x._1.split(";").toSeq))   //converting the lines to Row of sequences

//finally creating dataframe
val df = sqlContext.createDataFrame(rows, schema)
df.show(false)

który powinien ci dać

+-------+-------+-------+
|col1   |col2   |col3   |
+-------+-------+-------+
|column1|column2|column3|
|column1|column2|column3|
+-------+-------+-------+