I have a dataframe in Pyspark as:
listA = [(1,'AAA','USA'),(2,'XXX','CHN'),(3,'KKK','USA'),(4,'PPP','USA'),(5,'EEE','USA'),(5,'HHH','THA')]
df = spark.createDataFrame(listA, ['id', 'name','country'])
and I have created a dictionary as:
thedict={"USA":"WASHINGTON","CHN":"BEIJING","DEFAULT":"KEY NOT FOUND"}
and Then I created a UDF to get the matching key values from dictionary.
def my_func(letter):
if(thedict.get(letter) !=None):
return thedict.get(letter)
else:
return thedict.get("DEFAULT")
I am getting below error when trying to call function as:
df.withColumn('CAPITAL',my_func(df.country))
File "<stdin>", line 1, in <module>
File "/usr/hdp/current/spark2-client/python/pyspark/sql/dataframe.py", line 1848, in withColumn
assert isinstance(col, Column), "col should be Column"
AssertionError: col should be Column
Whereas if I embedded it with pyspark.sql.functions, it's working fine.
from pyspark.sql.functions import col, udf
udfdict = udf(my_func,StringType())
df.withColumn('CAPITAL',udfdict(df.country)).show()
+---+----+-------+-------------+
| id|name|country| CAPITAL|
+---+----+-------+-------------+
| 1| AAA| USA| WASHINGTON|
| 2| XXX| CHN| BEIJING|
| 3| KKK| USA| WASHINGTON|
| 4| PPP| USA| WASHINGTON|
| 5| EEE| USA| WASHINGTON|
| 5| HHH| THA|KEY NOT FOUND|
+---+----+-------+-------------+
I couldn't understand what is the difference in these two calls?
UDFand then use it!add_columnand without usingudfapply it on columns?udfto your work gets done!