【问题标题】:How to load the csv file into the Spark DataFrame with Array[Int]如何使用 Array[Int] 将 csv 文件加载到 Spark DataFrame 中
【发布时间】:2017-12-15 02:26:59
【问题描述】:

我的 csv 文件中每一行的结构如下:

u001, 2013-11, 0, 1, 2, ... , 99

其中u0012013-11是UID和日期,099的数字是数据值。我想将此 csv 文件加载到此结构中的 Spark DataFrame 中:

+-------+-------------+-----------------+
|    uid|         date|       dataVector|
+-------+-------------+-----------------+
|   u001|      2013-11|  [0,1,...,98,99]|
|   u002|      2013-11| [1,2,...,99,100]|
+-------+-------------+-----------------+

root
 |-- uid: string (nullable = true)
 |-- date: string (nullable = true)
 |-- dataVecotr: array (nullable = true)
 |    |-- element: integer (containsNull = true)

其中dataVector是Array[Int],并且dataVector长度对于所有的UID和日期都是一样的。 我尝试了几种方法来解决这个问题,包括

  1. 使用 shema

    val attributes = Array("uid", "date", "dataVector)
    val schema = StructType(
    StructField(attributes(0), StringType, true) ::
    StructField(attributes(1), StringType, true) ::
    StructField(attributes(2), ArrayType(IntegerType), true) :: 
    Nil)
    

但这种方式效果不佳。由于我后期数据集中的数据列大于100,我认为手动创建包含整个dataVector列的模式也很不方便。

  1. 直接加载不带schema的csv文件,使用concatenate multiple columns into single columns中的方法将数据的列串联在一起,但是schema结构是这样的

     root
      |-- uid: string (nullable = true)
      |-- date: string (nullable = true)
      |-- dataVector: struct (nullable = true)
      |    |-- _c3: string (containsNull = true)
      |    |-- _c4: string (containsNull = true)
      .
      .
      .
      |    |-- _c101: string (containsNull = true)
    

这仍然与我需要的不同,我没有找到将这个结构转换为我需要的方法。 所以我的问题是如何将 csv 文件加载到我需要的结构中?

【问题讨论】:

    标签: scala csv apache-spark


    【解决方案1】:

    加载它而不添加任何内容

    val df = spark.read.csv(path)
    

    然后选择:

    import org.apache.spark.sql.functions._
    import org.apache.spark.sql.Column
    
    // Combine data into array
    val dataVector: Column = array(
      df.columns.drop(2).map(col): _*  // Skip first 2 columns
    ).cast("array<int>")  // Cast to the required type
    val cols: Array[Column] = df.columns.take(2).map(col) :+ dataVector
    
    df.select(cols: _*).toDF("uid", "date", "dataVector")
    

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 2022-12-04
      • 2019-12-09
      相关资源
      最近更新 更多