在 Pyspark 中用随机数填充 na

Sha*_*ouz 1 random dataframe pyspark

我正在使用 Pyspark DataFrame。

我想用 14 到 46 范围内的随机值更新Age列中的NA 值。

我该怎么做?

小智 5

如果您想用相同的随机数替换空值,Mara 的答案是正确的,但如果您想要每个年龄的随机值,您应该执行合并和 F.rand() 操作,如下所示:

from pyspark.sql import functions as F
from pyspark.sql.types import IntegerType
from random import randint

df = sqlContext.createDataFrame(
    [(1, "a", 23.0), (3, "B", -23.0)], ("x1", "x2", "x3"))

df = (df
    .withColumn("x4", F.lit(None).cast(IntegerType()))
    .withColumn("x5", F.lit(None).cast(IntegerType()))
    )
    
df.na.fill({'x4':randint(0,100)}).show()
df.withColumn('x5', F.coalesce(F.col('x5'), (F.round(F.rand()*100)))).show()


+---+---+-----+---+----+
| x1| x2|   x3| x4|  x5|
+---+---+-----+---+----+
|  1|  a| 23.0|  9|null|
|  3|  B|-23.0|  9|null|
+---+---+-----+---+----+
+---+---+-----+----+----+
| x1| x2|   x3|  x4|  x5|
+---+---+-----+----+----+
|  1|  a| 23.0|null|44.0|
|  3|  B|-23.0|null| 2.0|
+---+---+-----+----+----+
Run Code Online (Sandbox Code Playgroud)