在python中对多个and条件使用when语句

2024-04-23 08:15:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据如下

+------------+--------------+---------------+    
|domain      | country_code | country       | 
+------------+--------------+---------------+
|amazon.de   | DE           | Germany       |
|amazon.uk   | UK           | united kingdom|
|amazon.de   | UK           | mismatched    |
|amazon.uk   | DE           | mismatched    |
+------------+--------------+---------------+

在上面的数据中,我想更正country\u代码,因此在domain列中包含.de的任何内容都应该与country\u代码列进行检查,如果country\u代码包含de,则是正确的匹配。否则就是不正确的

因此,我试图创建一个新的专栏国家如下。但是,我无法在使用when时使用and语句。你能帮忙吗

import pyspark.sql.functions as f

df = df.withColumn(
    'country', 
    f.when(
        f.col('domain') == '.de' && f.col('country_code') == 'DE',
        'Germany'
    ).otherwise('mismatch')
)

Tags: 数据代码amazondfdomaincodedecol