首页 > 解决方案 > 向数据框中添加一个新列,该列将指示另一列是否包含单词 pyspark

问题描述

我有一个数据框,我想向其中添加一个列,该列将指示单词“yes”是否在该行文本列中(如果单词在该行中,则为 1,如果不是,则为 0)我需要仅在以下情况下检查 1 “是”显示为一个单词而不是子字符串,或者如果“是”在标点符号旁边(例如:是!)我怎么能在火花中做到这一点?例如:

id  group  text
1   a       hey there
2   c       no you can
3   a       yes yes yes
4   b       yes or no
5   b       you need to say yes.
6   a       yes you can
7   d       yes!
8   c       no&
9   b       ok

结果将是:

id  group  text                  check
1   a       hey there             0
2   c       no you can            0
3   a       yes yes yes           1
4   b       yes or no             1
5   b       you need to say yes.  1
6   a       yes you can           1
7   d       yes!                  1
8   c       no&                   0
9   b       ok                    0

标签: pythonsqldataframepysparkapache-spark-sql

解决方案


您可以检查rlike并转换为整数:

import pyspark.sql.functions as F
df.withColumn("check",F.col("text").rlike("yes").cast("Integer")).show()

+---+-----+--------------------+-----+
| id|group|                text|check|
+---+-----+--------------------+-----+
|  1|    a|           hey there|    0|
|  2|    c|          no you can|    0|
|  3|    a|         yes yes yes|    1|
|  4|    b|           yes or no|    1|
|  5|    b|you need to say yes.|    1|
|  6|    a|         yes you can|    1|
|  7|    d|                yes!|    1|
|  8|    c|                 no&|    0|
|  9|    b|                  ok|    0|
+---+-----+--------------------+-----+

对于已编辑的问题,您可以尝试higher order functions

import string
import re
pat = '|'.join([re.escape(i) for i in list(string.punctuation)])

(df.withColumn("text1",F.regexp_replace(F.col("text"),pat,""))
.withColumn("Split",F.split("text1"," "))
.withColumn("check",
  F.expr('''exists(Split,x-> replace(x,"","") = "yes")''').cast("Integer"))
.drop("Split","text1")).show()

+---+-----+--------------------+-----+
| id|group|                text|check|
+---+-----+--------------------+-----+
|  1|    a|           hey there|    0|
|  2|    c|          no you can|    0|
|  3|    a|         yes yes yes|    1|
|  4|    b|           yes or no|    1|
|  5|    b|you need to say yes.|    1|
|  6|    a|         yes you can|    1|
|  7|    d|                yes!|    1|
|  8|    c|                 no&|    0|
|  9|    b|               okyes|    0|
+---+-----+--------------------+-----+

推荐阅读