1

我正在尝试使用 spark df 在 spark 中读取 CSV 文件。该文件没有标题列,但我想要标题列。怎么做?不知道对不对,我写了这个命令-> val df = spark.read.format("csv").load("/path/genchan1.txt").show()

并将列名作为 _c0 和 _c1 作为列。然后我尝试使用以下方法将列名更改为所需的名称:val df1 = df.withColumnRenamed("_c0","Series"),但我得到“withColumnRenamed”不是单元上的成员。

PS:我已经导入了 spark.implicits._ 和 spark.sql.functions。

请帮助我知道是否有任何方法可以将列标题添加到数据集以及为什么我会遇到这个问题。

4

2 回答 2

3

返回类型showUnit. 请show从最后删除。

val df = spark.read.format("csv").load("/path/genchan1.txt")
df.show()

然后您可以使用所有 df 功能-

val df1 = df.withColumnRenamed("_c0","Series") 
于 2020-06-25T08:44:36.380 回答
1

如果您事先知道 CSV 文件的结构,则在将数据加载到其中时定义一个模式并将其附加到 df 是一个更好的解决方案。

快速参考的示例代码 -

import org.apache.spark.sql.types._

val customSchema = StructType(Array(
  StructField("Series", StringType, true),
  StructField("Column2", StringType, true),
  StructField("Column3", IntegerType, true),
  StructField("Column4", DoubleType, true))
)

val df = spark.read.format("csv")
.option("header", "false") #since your file does not have header
.schema(customSchema)
.load("/path/genchan1.txt")

df.show()
于 2020-06-25T12:09:58.543 回答