python - 向数据框中添加一个新列,该列将指示另一列是否包含单词 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
解决方案
您可以检查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|
+---+-----+--------------------+-----+
推荐阅读
- jsf - 从对话框 Primefaces 更新表单中的 dataTable
- kubernetes - 如何将 PersistentVolumeClaim 添加到运行 GitLab AutoDevops 的部署中?
- c# - 如何将 Json 值从 React.JS 推送到 .NET 抽象类?
- bootstrap-flask - bootstrap-flask 的多文件字段处理
- github - PR 触发器不适用于 Azure DevOps 和 GitHub
- twitter - Twitter + spring social ,身份验证错误
- reactjs - 如何将我自己的 GeoJSON 数据添加到 Leaflet-realtime?
- kubernetes - k8s中如何判断一个节点是master还是worker?
- asp.net-core - 如何在 ASP.NET Core 中使用 opentelemetry 跟踪数据库操作?
- ios - 新类或结构的 Swift 文件