Skip to main content
 首页 » 编程设计

python之使用 pyspark UDF 替换电话号码中的字符

2025年05月04日28飞鱼

我已经编写了一个 pyspark 代码来执行以下操作,但它没有按预期工作。谁能指出我的错误

# Data cleaning function 
def clean_data(data): 
    rep = data.replace('/','') 
    rep = data.replace('-','') 
    rep = data.replace('+','') 
    rep = data.replace(' ','') 
    return  rep 
 
#clean_data_udf_int = udf(lambda z: clean_data(z), StringType()) 
#con.show(4) 
clean_data_udf = udf(clean_data, StringType()) 
con = con.withColumn('ph1_f',clean_data_udf('phone1')) 

输入数据框是错误的:

id phone phone1 
1  098     /90 
2  + 91    -90 

我想要数据框的输出是:

id phone phone1 
1  98     90 
2  91     90 

请您参考如下方法:

在这种情况下,您最好使用 pyspark.sql.functions.regexp_replace()而不是 using a udf .

from pyspark.sql.functions import col, regexp_replace 
 
def clean_data(data): 
    rep = regexp_replace(data, "[\/\-\+ ]", '') 
    rep = regexp_replace(rep, "^0", '') 
    return rep 
 
df = df.select( 
    "id",  
    clean_data(col("phone")).alias("phone"), 
    clean_data(col("phone1")).alias("phone1") 
) 
df.show() 
#+---+-----+------+ 
#| id|phone|phone1| 
#+---+-----+------+ 
#|  1|   98|    90| 
#|  2|   91|    90| 
#+---+-----+------+ 

由于部分要替换的字符在正则表达式中有特殊含义,需要用\进行转义。

第一个模式表示:

  • [\/\-\+ ]:匹配["/", "-", "+", ""]中的单个字符

第二个替换模式意味着:

  • ^0:替换字符串开头的 0。如果您希望有多个前导 0,您可以将其更改为 ^0+。