如何在不使用 Scala 案例类的情况下为 CSV 文件指定架构? [英] How to specify schema for CSV file without using Scala case class?

查看:21
本文介绍了如何在不使用 Scala 案例类的情况下为 CSV 文件指定架构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 CSV 文件加载到 DataFrame 中,如下所示.

I am loading a CSV file into a DataFrame as below.

val conf=new SparkConf().setAppName("dataframes").setMaster("local")
val sc=new SparkContext(conf)
val spark=SparkSession.builder().getOrCreate()
import spark.implicits._

val df = spark.
  read.  
  format("org.apache.spark.csv").
  option("header", true).
  csv("/home/cloudera/Book1.csv")
scala> df.printSchema()
root
 |-- name: string (nullable = true)
 |-- address: string (nullable = true)
 |-- age: string (nullable = true)

如何将 age 列更改为 Int 类型?

How to change age column to be of type Int?

推荐答案

inferSchema 选项可以通过以下方式自动识别变量的类型:

There is inferSchema option to automatically recognize the type of the variable by:

val df=spark.read
  .format("org.apache.spark.csv")
  .option("header", true)
  .option("inferSchema", true) // <-- HERE
  .csv("/home/cloudera/Book1.csv")

spark-csv 最初是 databricks 的一个外部库,但从 spark 2.0 版开始包含在核心 spark 中.您可以参考图书馆的github页面上的文档以查找可用选项.

spark-csv originally was an external library by databricks, but included in core spark from spark version 2.0 onwards. You can refer to documentation on the library's github page to find the available options.

这篇关于如何在不使用 Scala 案例类的情况下为 CSV 文件指定架构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆