我在Scala中使用Apache Spark。
我有一个csv文件,该文件在第一行中没有列名。就像这样:
28,Martok,49,476
29,Nog,48,364
30,Keiko,50,175
31,Miles,39,161
这些列代表ID,名称,年龄,numOfFriends。
在我的Scala对象中,我正在使用csv文件中的SparkSession创建数据集,如下所示:
val spark = SparkSession.builder.master("local[*]").getOrCreate()
val df = spark.read.option("inferSchema","true").csv("../myfile.csv")
df.printSchema()
当我运行程序时,结果是:
|-- _c0: integer (nullable = true)
|-- _c1: string (nullable = true)
|-- _c2: integer (nullable = true)
|-- _c3: integer (nullable = true)
如何在数据集中的列中添加名称?
最佳答案
读取CSV文件时,可以使用toDF
指定列名:
val df = spark.read.option("inferSchema","true").csv("../myfile.csv").toDF(
"ID", "name", "age", "numOfFriends"
)
或者,如果您已经创建了DataFrame,则可以按以下方式重命名其列:
val newColNames = Seq("ID", "name", "age", "numOfFriends")
val df2 = df.toDF(newColNames: _*)
关于scala - 将列名添加到从csv文件读取的数据中而没有列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120778/