注意:這是Spark版本2.1.1.2.6.1.0-129
我有一個火花資料框。其中一列將州作為字串型別(例如伊利諾伊州、加利福尼亞州、內華達州)。此列中有一些數字實體(例如 12、24、01、2)。我想用 a 替換整數的任何實體NULL。
以下是我撰寫的一些代碼:
my_df = my_df.selectExpr(
" regexp_replace(states, '^-?[0-9] $', '') AS states ",
"someOtherColumn")
此正則運算式用空字串替換整數的任何實體。我想用 python 中的 None 替換它以將其指定為NULLDataFrame 中的值。
uj5u.com熱心網友回復:
我強烈建議您查看PySpark SQL 函式,并嘗試正確使用它們而不是selectExpr
from pyspark.sql import functions as F
(df
.withColumn('states', F
.when(F.regexp_replace(F.col('states'), '^-?[0-9] $', '') == '', None)
.otherwise(F.col('states'))
)
.show()
)
# Output
# ---------- ------------
# | states|states_fixed|
# ---------- ------------
# | Illinois| Illinois|
# | 12| null|
# |California| California|
# | 01| null|
# | Nevada| Nevada|
# ---------- ------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/336462.html
