I have 2 spark dfs that are of different column size and partly different columns.
sdf1 = ['colA','colB','colC','colD','coldE','colF','colG','colH']
sdf2 = ['colA','colB','colI','colJ']
I would like to add columns from sdf1 that are missing in sdf2, and vice versa what I expect to get after that are:
sdf1 = ['colA','colB','colC','colD','coldE','colF','colG','colH','colI','colJ']
sdf2 = ['colA','colB','colI','colC','colD','coldE','colF','colG','colH','colJ']
when I followed the suggested approached from https://www.geeksforgeeks.org/merge-two-dataframes-with-different-amounts-of-columns-in-pyspark/ or from https://sparkbyexamples.com/spark/spark-merge-two-dataframes-with-different-columns/ ,
#Add missing columns to df1
from pyspark.sql.functions import lit
for column in [column for column in sdf2.columns if column not in sdf1.columns]:
df1 = sdf1.withColumn(column, lit(None))
#Add missing columns to df2
for column in [column for column in sdf1.columns if column not in sdf2.columns]:
df2 = sdf2.withColumn(column, lit(None))
sdf1 resulted to what I expect but not with sdf2, where I get:
df2 = ['colA','colB','colI','colJ','colH']
only the last column name was copied. Am I missing something that explains this? My goal is to merge both and I think I cannot do it without the same columns in pyspark