I'm trying to sort within partitions based on a column that contains nulls.
This DataFrame can be created as follows:
df = spark.createDataFrame(
[("2019-01-01", 5),
("2019-01-01", 20),
("2019-01-01", 10),
("2019-01-03", 1),
("2019-01-03", None),
("2019-01-03", None),
("2019-01-03", 2),
("2019-01-05", 10)],
("Date", "value")
)
Which looks like:
+----------+-----+
| Date|value|
+----------+-----+
|2019-01-01| 5|
|2019-01-01| 20|
|2019-01-01| 10|
|2019-01-03| 1|
|2019-01-03| null|
|2019-01-03| null|
|2019-01-03| 2|
|2019-01-05| 10|
+----------+-----+
Now I would like to rank each value from 1 to N per date. Which I attempt to do with the following code:
w = Window.partitionBy("date").orderBy("value")
df = df.withColumn("rank", F.dense_rank().over(w))
However, this apparently ranks all null values as 1, regardless of how many null values there are in a column:
+----------+-----+----+
| Date|value|rank|
+----------+-----+----+
|2019-01-03| null| 1|
|2019-01-03| null| 1|
|2019-01-03| 1| 2|
|2019-01-03| 2| 3|
|2019-01-05| 10| 1|
|2019-01-01| 5| 1|
|2019-01-01| 10| 2|
|2019-01-01| 20| 3|
+----------+-----+----+
How can I change the behavior of dense_rank() such that it keeps null values at null when ranking, instead of giving these values an arbitrary rank of 1?