apache-spark - 如何使用 PySpark 在另一列中查找子字符串列的位置?
问题描述
如果我有一个带有两列的 PySpark DataFrame,text
并且subtext
, 那么 where 肯定subtext
会出现在text
. 我将如何计算列中的subtext
位置text
?
输入数据:
+---------------------------+---------+
| text | subtext |
+---------------------------+---------+
| Where is my string? | is |
| Hm, this one is different | on |
+---------------------------+---------+
预期输出:
+---------------------------+---------+----------+
| text | subtext | position |
+---------------------------+---------+----------+
| Where is my string? | is | 6 |
| Hm, this one is different | on | 9 |
+---------------------------+---------+----------+
注意:我可以毫无问题地使用静态文本/正则表达式来执行此操作,我无法找到任何资源来使用特定于行的文本/正则表达式来执行此操作。
解决方案
您可以使用locate
. 您需要减去 1,因为字符串索引从 1 开始,而不是 0。
import pyspark.sql.functions as F
df2 = df.withColumn('position', F.expr('locate(subtext, text) - 1'))
df2.show(truncate=False)
+-------------------------+-------+--------+
|text |subtext|position|
+-------------------------+-------+--------+
|Where is my string? |is |6 |
|Hm, this one is different|on |9 |
+-------------------------+-------+--------+
推荐阅读
- python - 从先前函数返回的字典中打印键
- docker - 在 Bitnami Docker 容器中设置用户 UID
- html - 我可以使容器的悬停背景颜色大于其父容器吗
- c - 自 MacBook Pro 2015 上的 macOS Sierra 以来,编译 C 代码的速度大大降低
- vba - 在 vba 中不使用 sendkeys 在 SaveAs 窗口中设置 Excel 文件的文件名
- r - 使用 R 根据先前存在的文件夹顺序创建文件夹
- ios - UIImagePicker 初始化时间太长
- php - 使用 PHP 清理存储在变量中的 XML?
- html - 在 R Shiny 中的 DataTables 中嵌入 HTML5 小部件
- javascript - 传递给过滤器方法的布尔参数是什么?