python – 当列表值与Pyspark数据帧中的列值的子字符串匹配时,填充新列

weixin_38061494 2019-09-12 02:14:28
我在Pyspark有一个数据框,如下所示 df.show() +---+----------------------+ | id| con| +---+----------------------+ | 3| mac,mac pro| | 1| iphone5,iphone| | 1| android,android phone| | 1| windows,windows pc| | 1| spy camera,spy camera| | 2| camera,| | 3| cctv,cctv| | 2| apple iphone,iphone| | 3| ,spy camera| +---+----------------------+ 我想基于某些列表创建新列.列表如下 phone_list = ['iphone', 'android', 'nokia'] pc_list = ['windows', 'mac'] 条件: if a element in a list matches a string/substring in a column then flag the column to the value of that particular list 基本上我想要的是在phone_list中我有元素iphone,所以应该匹配id 1,其中con是iphone5,iphone和旗帜作为手机等等. 预期结果 +---+----------------------+------+----+ | id| con| cat| abc| +---+----------------------+------+----+ | 3| mac,mac pro| null| pc| | 1| iphone5,iphone|phones|null| | 1| android,android phone|phones|null| | 1| windows,windows pc| null| pc| | 1| spy camera,spy camera| null|null| | 2| camera,| null|null| | 3| cctv,cctv| null|null| | 2| apple iphone,iphone|phones|null| | 3| ,spy camera| null|null| +---+----------------------+------+----+ 我在下面做了. df1 = df.withColumn('cat', F.when(df.con.isin(phone_list), 'phones')).withColumn('abc', F.when(df.con.isin(pc_list), 'pc')) 产量 df1.show() +---+----------------------+----+----+ | id| con| cat| abc| +---+----------------------+----+----+ | 3| mac,mac pro|null|null| | 1| iphone5,iphone|null|null| | 1| android,android phone|null|null| | 1| windows,windows pc|null|null| | 1| spy camera,spy camera|null|null| | 2| camera,|null|null| | 3| cctv,cctv|null|null| | 2| apple iphone,iphone|null|null| | 3| ,spy camera|null|null| +---+----------------------+----+----+ 我怎样才能以正确的方式进行这种比较?
...全文
78 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38066085 2019-09-12
  • 打赏
  • 举报
回复
最好的方法是避免使用udf并使用pyspark.sql.Column.rlike().如果列与参数中包含的正则表达式匹配,则返回True. 在这种情况下,您可以使用“|”.join(list_of_terms)创建一个匹配列表中任何单词的正则表达式模式. (“|”是OR运算符) from pyspark.sql.functions import col, when df.select( "*", when(col("con").rlike("|".join(phone_list)), "phones").alias("cat"), when(col("con").rlike("|".join(pc_list)), "pc").alias("abc") ).show(truncate=False) #+---+---------------------+------+----+ #|id |con |cat |abc | #+---+---------------------+------+----+ #|3 |mac,mac pro |null |pc | #|1 |iphone5,iphone |phones|null| #|1 |android,android phone|phones|null| #|1 |windows,windows pc |null |pc | #|1 |spy camera,spy camera|null |null| #|2 |camera, |null |null| #|3 |cctv,cctv |null |null| #|2 |apple iphone,iphone |phones|null| #|3 |,spy camera |null |null| #+---+---------------------+------+----+ 我们还使用了如果没有指定otherwise()条件,pyspark.sql.functions.when()将返回null的事实.

433

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧