Spark의 데이터 프레임 열에있는 영숫자 값에서 알파벳 제거

Aug 18 2020

데이터 프레임의 두 열은 다음과 같습니다.

SKU   | COMPSKU

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

스칼라로 불꽃

모든 영문자를 제거하고 숫자 만 유지하려면 어떻게해야합니까 ..

예상 출력 :

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

답변

Shu Aug 18 2020 at 20:40

regexp_replace함수로 시도한 다음 케이스 when otherwise statement 를 사용하여 빈 값을 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

이 방법으로도 할 수 있습니다.

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