I currently have the following code:
def _join_intent_types(df):
mappings = {
'PastNews': 'ContextualInformation',
'ContinuingNews': 'News',
'KnownAlready': 'OriginalEvent',
'SignificantEventChange': 'NewSubEvent',
}
return df.withColumn('Categories', posexplode('Categories').alias('i', 'val'))\
.when(col('val').isin(mappings), mappings[col('i')])\
.otherwise(col('val'))
But I'm not sure if my syntax is right. What I'm trying to do is operate on a column of lists such as:
['EmergingThreats', 'Factoid', 'KnownAlready']
and replace strings within that Array with the mappings in the dictionary provided, i.e.
['EmergingThreats', 'Factoid', 'OriginalEvent']
I understand this is possible with a UDF but I was worried how this would impact performance and scalability.
A sample of the original table:
+------------------+-----------------------------------------------------------+
|postID |Categories |
+------------------+-----------------------------------------------------------+
|266269932671606786|[EmergingThreats, Factoid, KnownAlready] |
|266804609954234369|[Donations, ServiceAvailable, ContinuingNews] |
|266250638852243457|[EmergingThreats, Factoid, ContinuingNews] |
|266381928989589505|[EmergingThreats, MultimediaShare, Factoid, ContinuingNews]|
|266223346520297472|[EmergingThreats, Factoid, KnownAlready] |
+------------------+-----------------------------------------------------------+
I'd like the code to replace strings in those arrays with their new mappings, provided they exist in the dictionary. If not, leave them as they are:
+------------------+-------------------------------------------------+
|postID |Categories |
+------------------+-------------------------------------------------+
|266269932671606786|[EmergingThreats, Factoid, OriginalEvent] |
|266804609954234369|[Donations, ServiceAvailable, News] |
|266250638852243457|[EmergingThreats, Factoid, News] |
|266381928989589505|[EmergingThreats, MultimediaShare, Factoid, News]|
|266223346520297472|[EmergingThreats, Factoid, OriginalEvent] |
+------------------+-------------------------------------------------+