简体   繁体   English

Spark DataFrames 联盟

[英]Union of Spark DataFrames

I've tried this code to add a row to a dataframe if df2 is empty but I get this error and I don't understand the reason.如果 df2 为空,我已尝试使用此代码向数据框添加一行,但我收到此错误并且我不明白原因。 I don't have any column called value.我没有任何名为 value 的列。

Exception in thread "main" java.lang.IllegalArgumentException: requirement failed: The number of columns doesn't match.线程“main”java.lang.IllegalArgumentException 中的异常:要求失败:列数不匹配。 Old column names (1): value New column names (2): country, code旧列名 (1):值 新列名 (2):国家、代码

var df1 = Seq.empty[(String,String)].toDF("country","code").

val df2 = spark.emptyDataFrame

if (df2.isEmpty) df1 = df1.union(Seq("GLOBAL" , "EMPTY").toDF("country","code"))

Dataframes, like datasets and RDDs, are immutable.数据帧,如数据集和 RDD,是不可变的。 So you need to create a new Dataframe when appending a row to it.因此,您需要在向其附加一行时创建一个新的 Dataframe。 The Dataframe union() method is used to combine two DataFrames of the same structure or schema. Dataframe union()方法用于组合两个相同结构或模式的DataFrame。 If schemas are not the same it returns an error.如果模式不同,则返回错误。

To respect the schemas, you need to use the union method on df1 .要尊重模式,您需要在df1上使用union方法。 To create a new DataFrame with the row you want you should use something like:要使用您想要的行创建一个新的 DataFrame,您应该使用以下内容:

 val df3 = df1.union(Seq("GLOBAL" , "EMPTY").toDF())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM