我有兩列有一些文字:
| 文本1 | text_2 |
|---|---|
| astro 流明 宇宙 行星 | 縮影 天文學 行星 大小 |
text_1如果該單詞出現在text_2列中(即完全重復)或者是列中某個單詞的一部分,我需要從列中洗掉該單詞text_2。
期望的輸出:
| 文本1 | text_2 |
|---|---|
| 流明 | 縮影 天文學 行星 大小 |
如何在 PostgreSQL 和 PySpark 中做到這一點?
uj5u.com熱心網友回復:
您可以將第一列拆分為單詞陣列,然后使用filter如下函式過濾陣列:
from pyspark.sql import functions as F
df = spark.createDataFrame(
[("astro lumen cosm planet", "microcosm astronomy planet magnitude")],
["text_1", "text_2"]
)
df1 = df.withColumn(
"text_1",
F.array_join(
F.filter(F.split("text_1", "\\s "), lambda x: ~F.col("text_2").contains(x)),
" "
)
)
df1.show(truncate=False)
# ------ ------------------------------------
#|text_1|text_2 |
# ------ ------------------------------------
#|lumen |microcosm astronomy planet magnitude|
# ------ ------------------------------------
注意3.1 之前的spark,需要用到expr高階函式filter
uj5u.com熱心網友回復:
這是在 SQL 中執行此操作的一種方法:
WITH data AS (
SELECT 'astro lumen cosm planet' AS needles,
'microcosm astronomy planet magnitude' AS haystack
)
SELECT string_agg(needle.n, ' ')
FROM data
CROSS JOIN LATERAL regexp_split_to_table(data.needles, ' ') AS needle(n)
WHERE strpos(data.haystack, needle.n) = 0;
string_agg
════════════
lumen
(1 row)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477967.html
標籤:细绳 PostgreSQL 阿帕奇火花 pyspark apache-spark-sql
上一篇:僅為類的子類鍵入
