在pyspark中,可以用另一列填充吗?

foo*_*bar 3 apache-spark pyspark

假设有一个RDD看起来像这样:

+----+--------------+-----+
| age|best_guess_age| name|
+----+--------------+-----+
|  23|            23|Alice|
|null|            18|  Bob|
|  34|            32|  Tom|
|null|            40|Linda|
+----+--------------+-----+
Run Code Online (Sandbox Code Playgroud)

每当它为null时,我们想agebest_guess_age列填充该列的位置。

fillna命令需要一个实际值来替换na,我们不能简单地传递一个列。

这该怎么做?

Psi*_*dom 5

您可以使用coalesce功能;这样做coalesce('age', 'best_guess_age')age如果它不为null,它将从列中获取值,否则从best_guess_age列中获取:

from pyspark.sql.functions import coalesce
df.withColumn('age', coalesce('age', 'best_guess_age')).show()
+---+--------------+-----+
|age|best_guess_age| name|
+---+--------------+-----+
| 23|            23|Alice|
| 18|            18|  Bob|
| 34|            32|  Tom|
| 40|            40|Linda|
+---+--------------+-----+
Run Code Online (Sandbox Code Playgroud)