Pla*_*cid 5 csv scala apache-spark apache-spark-sql
我正在使用Apache Spark和Scala.
我有一个csv文件,第一行没有列名.就像这样:
28,Martok,49,476
29,Nog,48,364
30,Keiko,50,175
31,Miles,39,161
Run Code Online (Sandbox Code Playgroud)
列表示ID,名称,年龄,numOfFriends.
在我的Scala对象中,我使用来自csv文件的SparkSession创建数据集,如下所示:
val spark = SparkSession.builder.master("local[*]").getOrCreate()
val df = spark.read.option("inferSchema","true").csv("../myfile.csv")
df.printSchema()
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,结果是:
|-- _c0: integer (nullable = true)
|-- _c1: string (nullable = true)
|-- _c2: integer (nullable = true)
|-- _c3: integer (nullable = true)
Run Code Online (Sandbox Code Playgroud)
如何在数据集中的列中添加名称?
Leo*_*o C 16
您可以toDF在读取CSV文件时指定列名称:
val df = spark.read.option("inferSchema","true").csv("../myfile.csv").toDF(
"ID", "name", "age", "numOfFriends"
)
Run Code Online (Sandbox Code Playgroud)
或者,如果您已经创建了DataFrame,则可以按如下方式重命名其列:
val newColNames = Seq("ID", "name", "age", "numOfFriends")
val df2 = df.toDF(newColNames: _*)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4913 次 |
| 最近记录: |