【问题标题】:Selecting multiple arbitrary columns from Scala array using map()使用 map() 从 Scala 数组中选择多个任意列
【发布时间】:2023-04-11 07:34:01
【问题描述】:

我是 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
}

有没有一种方法可以将任意数量的列索引传递给数组中的函数?

【问题讨论】:

    标签: scala csv apache-spark


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多