【发布时间】:2020-04-18 00:35:50
【问题描述】:
我目前有以下代码:
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'))
但我不确定我的语法是否正确。我要做的是对一列列表进行操作,例如:
['EmergingThreats', 'Factoid', 'KnownAlready']
并用提供的字典中存在的映射替换该数组中的字符串,即。
['EmergingThreats', 'Factoid', 'OriginalEvent']
我尝试了多种方法,但似乎无法应用转换,任何帮助将不胜感激。我知道使用 UDF 可以做到这一点,但我担心这会如何影响性能和可扩展性。
更新: 我在下面提供了原始表结构的示例,
+------------------+-----------------------------------------------------------+
|postID |Categories |
+------------------+-----------------------------------------------------------+
|266269932671606786|[EmergingThreats, Factoid, KnownAlready] |
|266804609954234369|[Donations, ServiceAvailable, ContinuingNews] |
|266250638852243457|[EmergingThreats, Factoid, ContinuingNews] |
|266381928989589505|[EmergingThreats, MultimediaShare, Factoid, ContinuingNews]|
|266223346520297472|[EmergingThreats, Factoid, KnownAlready] |
+------------------+-----------------------------------------------------------+
如果这些数组中的字符串存在于字典中,我想要代码用它们的新映射替换它们。如果没有,请保持原样:
+------------------+-------------------------------------------------+
|postID |Categories |
+------------------+-------------------------------------------------+
|266269932671606786|[EmergingThreats, Factoid, OriginalEvent] |
|266804609954234369|[Donations, ServiceAvailable, News] |
|266250638852243457|[EmergingThreats, Factoid, News] |
|266381928989589505|[EmergingThreats, MultimediaShare, Factoid, News]|
|266223346520297472|[EmergingThreats, Factoid, OriginalEvent] |
+------------------+-------------------------------------------------+
【问题讨论】:
-
你使用的是哪个 spark 版本?
-
@SreeramTP 版本 2.4.5
标签: apache-spark pyspark