Aarti Agarwal
Aarti Agarwal

Reputation: 49

Removing alphabets from alphanumeric values present in column of dataframe of spark

The two column of dataframe looks like.

SKU   | COMPSKU

PT25M | PT10M
PT3H  | PT20M
TH    | QR12
S18M  | JH

spark with scala

How can i remove all alphabets and only numbers retain..

Expected output:

25|10
3|20
0|12
18|0

Upvotes: 1

Views: 845

Answers (2)

jayrythium
jayrythium

Reputation: 767

You could also do it this way.

df.withColumn(
    "SKU",
    when(regexp_replace(col("SKU"),"[a-zA-Z]","")==="",0
        ).otherwise(regexp_replace(col("SKU"),"[a-zA-Z]","")) 
).withColumn(
    "COMPSKU",
    when(regexp_replace(col("COMPSKU"),"[a-zA-Z]","")==="", 0
        ).otherwise(regexp_replace(col("COMPSKU"),"[a-zA-Z]",""))
).show()
/*
        +-----+-------+
        |  SKU|COMPSKU|
        +-----+-------+
        |  25 |  10   |
        |   3 |  20   |
        |   0 |  12   |
        |  18 |   0   |
        +-----+-------+
*/

Upvotes: 1

notNull
notNull

Reputation: 31460

Try with regexp_replace function then use case when otherwise statement to replace empty values with 0.

Example:

df.show()
/*
+-----+-------+
|  SKU|COMPSKU|
+-----+-------+
|PT25M|  PT10M|
| PT3H|  PT20M|
|   TH|   QR12|
| S18M|     JH|
+-----+-------+
*/

df.withColumn("SKU",regexp_replace(col("SKU"),"[a-zA-Z]","")).
withColumn("COMPSKU",regexp_replace(col("COMPSKU"),"[a-zA-Z]","")).
withColumn("SKU",when(length(trim(col("SKU")))===0,lit(0)).otherwise(col("SKU"))).
withColumn("COMPSKU",when(length(trim(col("COMPSKU")))===0,lit(0)).otherwise(col("COMPSKU"))).
show()

/*
+---+-------+
|SKU|COMPSKU|
+---+-------+
| 25|     10|
|  3|     20|
|  0|     12|
| 18|      0|
+---+-------+
*/

Upvotes: 0

Related Questions