python—向Dataframe添加一个新列,该列将指示另一列是否包含单词pyspark

dfddblmv  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(323)

我有一个数据框,我想添加一个列,它将指示单词“yes”是否在该行文本列中(如果单词在该行中,则为1;如果不在该行中,则为0)。只有当“yes”显示为单词而不是子字符串,或者如果“yes”位于标点符号旁边时,我才需要选中1(示例:yes!)我怎么能在spark做到呢?例如:

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
zhte4eai

zhte4eai1#

你可以和我核对一下 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|
+---+-----+--------------------+-----+
c9qzyr3d

c9qzyr3d2#

我需要把 1 仅当“是”作为单词而不是子字符串出现时才检查。
你可以通过匹配 text 反对使用单词边界的正则表达式( \b ). 这是一个方便的regex特性,它表示分隔单词(空格、标点符号等)的字符。
在sql中,您可以执行以下操作:

select
    t.*
    case when text rlike '\byes\b' then 1 else 0 end as check
from mytable t

相关问题