gpt4 book ai didi

excel - 如何读取多个 Excel 文件并将它们连接到一个 Apache Spark DataFrame 中?

转载 作者:行者123 更新时间:2023-12-02 17:42:29 25 4
gpt4 key购买 nike

最近我想做 Spark Summit 2016 的 Spark Machine Learning Lab。培训视频是 here并可导出笔记本here.

实验室使用的数据集可以从UCI Machine Learning Repository下载。它包含来自燃气发电厂中各种传感器的一组读数。格式为xlsx文件,共五张。

要在实验室中使用数据,我需要读取 Excel 文件中的所有工作表并将它们连接到一个 Spark DataFrame 中。在培训期间,他们使用 Databricks Notebook,但我使用 IntelliJ IDEA 和 Scala 并在控制台中评估代码。

第一步是将所有 Excel 工作表保存到名为 sheet1.xlxssheet2.xlsx 等的单独 xlsx 文件中,并将它们放入 sheets 目录。

如何读取所有 Excel 文件并将它们连接到一个 Apache Spark DataFrame 中?

最佳答案

为此我使用了 spark-excel包裹。可以将其添加到 build.sbt 文件中,如下所示:libraryDependencies += "com.crealytics"%% "spark-excel"% "0.8.2"

在 IntelliJ IDEA Scala 控制台中执行的代码是:

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{SparkSession, DataFrame}
import java.io.File

val conf = new SparkConf().setAppName("Excel to DataFrame").setMaster("local[*]")
val sc = new SparkContext(conf)
sc.setLogLevel("WARN")

val spark = SparkSession.builder().getOrCreate()

// Function to read xlsx file using spark-excel.
// This code format with "trailing dots" can be sent to IJ Scala Console as a block.
def readExcel(file: String): DataFrame = spark.read.
format("com.crealytics.spark.excel").
option("location", file).
option("useHeader", "true").
option("treatEmptyValuesAsNulls", "true").
option("inferSchema", "true").
option("addColorColumns", "False").
load()

val dir = new File("./data/CCPP/sheets")
val excelFiles = dir.listFiles.sorted.map(f => f.toString) // Array[String]

val dfs = excelFiles.map(f => readExcel(f)) // Array[DataFrame]
val ppdf = dfs.reduce(_.union(_)) // DataFrame

ppdf.count() // res3: Long = 47840
ppdf.show(5)

控制台输出:

+-----+-----+-------+-----+------+
| AT| V| AP| RH| PE|
+-----+-----+-------+-----+------+
|14.96|41.76|1024.07|73.17|463.26|
|25.18|62.96|1020.04|59.08|444.37|
| 5.11| 39.4|1012.16|92.14|488.56|
|20.86|57.32|1010.24|76.64|446.48|
|10.82| 37.5|1009.23|96.62| 473.9|
+-----+-----+-------+-----+------+
only showing top 5 rows

关于excel - 如何读取多个 Excel 文件并将它们连接到一个 Apache Spark DataFrame 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42748704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com