我有一个带有文本列和名称列的数据框。我想检查该名称是否存在于文本列中,以及是否存在将其替换为某个值。我希望以下内容能够发挥作用:
df = df.withColumn("new_text",regex_replace(col("text),col("name"),"NAME"))
Run Code Online (Sandbox Code Playgroud)
但 Column 不可迭代,因此它不起作用。我必须写一个 udf 才能做到这一点吗?那会是什么样子?
你已经快接近了。withColumn这是带有和选项的详细示例selectExpr:
样本 df
df = spark.createDataFrame([('This is','This'),
('That is','That'),
('That is','There')],
['text','name'])
#+-------+-----+
#| text| name|
#+-------+-----+
#|This is| This|
#|That is| That|
#|That is|There|
#+-------+-----+
Run Code Online (Sandbox Code Playgroud)
选项1: withColumn使用expr函数
from pyspark.sql.functions import expr, regexp_replace
df.withColumn("new_col1",expr("regexp_replace(text,name,'NAME')")).show()
#+-------+-----+--------+
#| text| name|new_col1|
#+-------+-----+--------+
#|This is| This| NAME is|
#|That is| That| NAME is|
#|That is|There| That is|
#+-------+-----+--------+
Run Code Online (Sandbox Code Playgroud)
选项 2: selectExpr使用regexp_replace
from pyspark.sql.functions import regexp_replace
df.selectExpr("*",
"regexp_replace(text,name,'NAME') AS new_text").show()
#+-------+-----+--------+
#| text| name|new_text|
#+-------+-----+--------+
#|This is| This| NAME is|
#|That is| That| NAME is|
#|That is|There| That is|
#+-------+-----+--------+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3890 次 |
| 最近记录: |