从spark数据帧列中的字母数字值中删除字母



数据帧的两列如下。

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

scala 火花

如何删除所有字母,只保留数字。。

预期输出:

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

您也可以这样做。

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

尝试使用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|
+---+-------+
*/

最新更新