Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

apache spark - How to split a number and add hyphen in a pyspark dataframe?

I want to split all numbers in a column.

number: 123456789012

to be 123-4567890-12

So I want to add - at positions 4 and 10.

I do not want to make new columns

question from:https://stackoverflow.com/questions/66066429/how-to-split-a-number-and-add-hyphen-in-a-pyspark-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use regexp_replace :

from pyspark.sql import functions as F

df1 = df.withColumn(
    "number",
    F.regexp_replace(F.col("number"), "(\d{3})(\d{7})(\d+)", "$1-$2-$3")
)

df1.show()

#+--------------+
#|        number|
#+--------------+
#|123-4567890-12|
#+--------------+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...