【发布时间】:2017-12-15 02:26:59
【问题描述】:
我的 csv 文件中每一行的结构如下:
u001, 2013-11, 0, 1, 2, ... , 99
其中u001和2013-11是UID和日期,0到99的数字是数据值。我想将此 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和日期都是一样的。 我尝试了几种方法来解决这个问题,包括
-
使用 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列的模式也很不方便。
-
直接加载不带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