0

I want to fill null values on a Spark df based on the values of the id column.

Pyspark df:

index id animal name
1 001 cat doug
2 002 dog null
3 001 cat null
4 003 null null
5 001 null doug
6 002 null bob
7 003 bird larry

Expected result:

index id animal name
1 001 cat doug
2 002 dog bob
3 001 cat doug
4 003 bird larry
5 001 cat doug
6 002 dog bob
7 003 bird larry

1 Answer 1

2

You can use last (or first) with window function.

from pyspark.sql import Window
from pyspark.sql import functions as F

w = Window.partitionBy('id')
df = (df.withColumn('animal', F.last('animal', ignorenulls=True).over(w))
      .withColumn('name', F.last('name', ignorenulls=True).over(w)))
      
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.