Метод regex_replace
предпочтителен, но вы также можете использовать udf
для этого:
from pyspark.sql.functions import col, udf
from pyspark.sql.Types import StringType
def remove_inner_zeroes(my_string):
if my_string[-1] == '0':
return my_string.replace('0', '') + '0'
return my_string.replace('0', '')
remove_inner_zeros_udf = udf(remove_inner_zeros, StringType())
df1.withColumn('zeroRemoved', remove_inner_zeros_udf(col('number')).show()
#+------+-----------+
#|number|zeroRemoved|
#+------+-----------+
#|GH0786| GH786|
#|HH7040| HH740|
#|IP0090| IP90|
#| AH567| AH567|
#+------+-----------+
Или вы можете повторить ту же функцию, используя следующие функции искры:
pyspark.sql.Columns.endsWith()
pyspark.sql.functions.replace()
pyspark.sql.functions.when()
pyspark.sql.functions.concat()
:
Например:
from pyspark.sql.functions import col, concat, lit, replace, when
def remove_inner_zeros_spark(string_col):
return when(
string_col.endsWith('0'),
concat(replace(string_col, '0', ''), lit('0'))
).otherwise(replace(string_col, '0', ''))
df1.withColumn('zeroRemoved', remove_inner_zeros_spark(col('number')).show()
#+------+-----------+
#|number|zeroRemoved|
#+------+-----------+
#|GH0786| GH786|
#|HH7040| HH740|
#|IP0090| IP90|
#| AH567| AH567|
#+------+-----------+