當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python pyspark DataFrame.unionByName用法及代碼示例

本文簡要介紹 pyspark.sql.DataFrame.unionByName 的用法。

用法:

DataFrame.unionByName(other, allowMissingColumns=False)

返回一個新的 DataFrame ,其中包含此行和另一個 DataFrame 中的行的聯合。

這與 SQL 中的 UNION ALLUNION DISTINCT 都不同。要執行 SQL-style 集合並集(對元素進行重複數據刪除),請使用此函數,後跟 distinct()

2.3.0 版中的新函數。

例子

此函數與 union() 之間的區別在於此函數按名稱(而不是按位置)解析列:

>>> df1 = spark.createDataFrame([[1, 2, 3]], ["col0", "col1", "col2"])
>>> df2 = spark.createDataFrame([[4, 5, 6]], ["col1", "col2", "col0"])
>>> df1.unionByName(df2).show()
+----+----+----+
|col0|col1|col2|
+----+----+----+
|   1|   2|   3|
|   6|   4|   5|
+----+----+----+

當參數 allowMissingColumnsTrue 時,此和其他 DataFrame 中的列名稱集可以不同;缺少的列將用 null 填充。此外,此 DataFrame 的缺失列將添加到聯合結果模式的末尾:

>>> df1 = spark.createDataFrame([[1, 2, 3]], ["col0", "col1", "col2"])
>>> df2 = spark.createDataFrame([[4, 5, 6]], ["col1", "col2", "col3"])
>>> df1.unionByName(df2, allowMissingColumns=True).show()
+----+----+----+----+
|col0|col1|col2|col3|
+----+----+----+----+
|   1|   2|   3|null|
|null|   4|   5|   6|
+----+----+----+----+

在 3.1.0 版中更改:添加了可選參數allowMissingColumns指定是否允許缺失列。

相關用法


注:本文由純淨天空篩選整理自spark.apache.org大神的英文原創作品 pyspark.sql.DataFrame.unionByName。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。