我想用Pyspark中的最后一行值填充Missing值:

时间:2018-10-11 12:06:36

标签: python pyspark lag

我的df有多列

我尝试过的查询:

df=df.withColumn('Column_required',F.when(df.Column_present>1,df.Column_present).otherwise(lag(df.Column_present))

否则无法继续工作。 。我要对其进行操作的列:

Column_present       Column_required
40000                 40000
Null                  40000
Null                  40000
500                   500
Null                  500
Null                  500

1 个答案:

答案 0 :(得分:1)

我认为您的解决方案可能是使用last而不是滞后:

df_new = spark.createDataFrame([
(1, 40000), (2, None),  (3,None), (4,None),
(5,500), (6,None), (7,None)
], ("id", "Col_present"))

df_new.withColumn('Column_required',when(df_new.Col_present>1,df_new.Col_present).otherwise(last(df_new.Col_present,ignorenulls=True).over(Window.orderBy("id")))).show()

这将产生您想要的输出:

+---+-----------+---------------+
| id|Col_present|Column_required|
+---+-----------+---------------+
|  1|      40000|          40000|
|  2|       null|          40000|
|  3|       null|          40000|
|  4|       null|          40000|
|  5|        500|            500|
|  6|       null|            500|
|  7|       null|            500|
+---+-----------+---------------+

但是请注意,window函数需要一列才能执行排序。这就是为什么我在示例中使用id列。如果您的数据框不包含带有monotonically_increasing_id()的可排序列,则可以自己创建一个id列。

相关问题