Rimozione di alfabeti dai valori alfanumerici presenti nella colonna del dataframe di spark

Aug 18 2020

Le due colonne di dataframe hanno l'aspetto.

SKU   | COMPSKU

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

scintilla con scala

Come posso rimuovere tutti gli alfabeti e conservare solo i numeri ..

Uscita prevista:

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

Risposte

Shu Aug 18 2020 at 20:40

Prova con la regexp_replacefunzione, quindi usa il caso when otherwise statement per sostituire i valori vuoti con 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|
+---+-------+
*/
1 jayrythium Aug 18 2020 at 21:15

Potresti anche farlo in questo modo.

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   |
        +-----+-------+
*/