การเลือกคอลัมน์ที่ต้องการหลายคอลัมน์จากอาร์เรย์ Scala โดยใช้ map ()

ฉันยังใหม่กับ Scala (และ Spark) ฉันกำลังพยายามอ่านในไฟล์ csv และแยกคอลัมน์หลายคอลัมน์ออกจากข้อมูล ฟังก์ชันต่อไปนี้ทำเช่นนี้ แต่มีดัชนีคอลัมน์แบบฮาร์ดโค้ด:

def readCSV(filename: String, sc: SparkContext): RDD[String] = {
  val input = sc.textFile(filename).map(line => line.split(","))
  val out = input.map(csv => csv(2)+","+csv(4)+","+csv(15))
  return out
}

มีวิธีใช้แผนที่โดยกำหนดจำนวนดัชนีคอลัมน์ที่ส่งผ่านไปยังฟังก์ชันในอาร์เรย์หรือไม่?


person yrjo    schedule 09.07.2015    source แหล่งที่มา


คำตอบ (1)


หากคุณมีลำดับของดัชนี คุณสามารถแมปทับลำดับนั้นแล้วส่งคืนค่า :

scala> val m = List(List(1,2,3), List(4,5,6))
m: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6))

scala> val indices = List(0,2)
indices: List[Int] = List(0, 2)

// For each inner sequence, get the relevant values
// indices.map(inner) is the same as indices.map(i => inner(i))
scala> m.map(inner => indices.map(inner))
res1: List[List[Int]] = List(List(1, 3), List(4, 6))

// If you want to join all of them use .mkString
scala> m.map(inner => indices.map(inner).mkString(","))
res2: List[String] = List(1,3, 4,6)  // that's actually a List containing 2 String
person Marth    schedule 09.07.2015