[英]How can I pass in a string from XML file as a join condition for dataFrames in Spark Using Scala?
[英]How can I join a list of Spark dataframes together in Scala?
我有Seq
火花dataframes(即Seq[org.apache.spark.sql.DataFrame]
它可以含有1個或多個元素。 每個數據框都有一個公用的列列表,每個數據框還具有一些其他列。 我想做的是使用聯接條件中的那些通用列將所有這些數據框聯接在一起(請記住,數據框的數量是未知的)
如何將所有這些數據框結合在一起? 我想我可以foreach
過他們,但似乎並不很優雅。 任何人都可以提出更實用的方法嗎? 編輯:遞歸函數比foreach更好,我現在正在研究中,完成后將其發布到此處 。
這是一些代碼,創建一個由n個數據幀組成的列表(在這種情況下,n = 3),每個數據幀包含id
和Product
列:
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
val conf = new SparkConf().setMaster("local[*]")
val spark = SparkSession.builder().appName("Feature Generator tests").config(conf).config("spark.sql.warehouse.dir", "/tmp/hive").enableHiveSupport().getOrCreate()
val df = spark.range(0, 1000).toDF().withColumn("Product", concat(lit("product"), col("id")))
val dataFrames = Seq(1,2,3).map(s => df.withColumn("_" + s.toString, lit(s)))
為了澄清, dataFrames.head.columns
返回Array[String] = Array(id, Product, _1)
。
我如何將這n個數據框一起連接到id
和Product
列上,以便返回的數據框具有Array[String] = Array(id, Product, _1, _2, _3)
?
dataFrames
是一個List
; 您可以使用List.reduce
方法連接內部的所有數據框:
dataFrames.reduce(_.join(_, Seq("id", "Product"))).show
//+---+---------+---+---+---+
//| id| Product| _1| _2| _3|
//+---+---------+---+---+---+
//| 0| product0| 1| 2| 3|
//| 1| product1| 1| 2| 3|
//| 2| product2| 1| 2| 3|
//| 3| product3| 1| 2| 3|
//| 4| product4| 1| 2| 3|
//| ... more rows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.