QuestionQ215

VerifiedDeveloping Apache Spark™ DataFrame/DataSet API Applications

A data engineer needs to append every row from one table to every row from another, but not every column in the first table exists in the second table. The error message is:

AnalysisException: [NUM_COLUMNS_MISMATCH] UNION can only be performed on inputs with the same number of columns  

The current code is:

anz_df = au_df.union(nz_df)  

The DataFrame au_df has one extra column that is absent from the DataFrame nz_df, but otherwise both DataFrames have identical column names and data types.

What should the data engineer change in the code to ensure that the combined DataFrame can be produced as expected?

Explanation

PySpark DataFrame.unionByName matches columns by name. Setting allowMissingColumns=True permits one DataFrame to contain an extra column and fills that missing column with NULL in rows from the other DataFrame, allowing all rows to be combined.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!