Given a table like the following:
+--+------------------+-----------+
|id| diagnosis_age| diagnosis|
+--+------------------+-----------+
| 1|2.1843037179180302| 315.320000|
| 1| 2.80033330216659| 315.320000|
| 1| 2.8222365762732| 315.320000|
| 1| 5.64822705794013| 325.320000|
| 1| 5.686557787521759| 335.320000|
| 2| 5.70572315231258| 315.320000|
| 2| 5.724888517103389| 315.320000|
| 3| 5.744053881894209| 315.320000|
| 3|5.7604813374292005| 315.320000|
| 3| 5.77993740687426| 315.320000|
+--+------------------+-----------+
I would like to reduce each id to just one row by selecting the diagnosis and age with the most frequent diagnosis.
output would look like:
+--+------------------+-----------+
|id| diagnosis_age| diagnosis|
+--+------------------+-----------+
| 1|2.1843037179180302| 315.320000|
| 2| 5.70572315231258| 315.320000|
| 3| 5.744053881894209| 315.320000|
+--+------------------+-----------+
I've tried things like:
SELECT id, diagnosis, age,
COUNT(distinct diagnosis) OVER (partition by id)
FROM table
But am not really getting anything to work!
using the below code:
wc=Window().partitionBy("id", "diagnosis").orderBy("diagnosis_age")
wc2=Window().partitionBy("id")
ddfc.withColumn("count", F.count("diagnosis").over(wc))\
.withColumn("max", F.max("count").over(wc2))\
.filter("count=max")\
.groupBy("id").agg(F.first("diagnosis_age").alias("diagnosis_age"), F.first("diagnosis").alias("diagnosis"))\
.orderBy("id")\
.groupBy("diagnosis")\
.count()\
.orderBy("count", ascending = False)\
.show(5)
I get:
+--------------+-----+
|diagnosis |count|
+--------------+-----+
| V20.2|22179|
| 382.900000|12985|
| 389.900000|11333|
| 381.810000| 7448|
| 493.900000| 3249|
+--------------+-----+
whereas your code (amended to group by diagnosis and get the 5 most frequent diagnosis) outputs:
+--------------+------+
|diagnosis |count |
+--------------+------+
| 389.900000 |13268 |
| 382.900000 | 7572 |
| V20.2 | 6193 |
| 381.810000 | 4735 |
| V72.19 | 4115 |
+--------------+------+
Appreciate the help.
In statistics, this is the most common value and it is called the mode.
You can use aggregation and row_number()
:
select id, diagnosis, age
from (select id, diagnosis, min(age) as age, count(*) as cnt,
row_number() over (partition by id order by count(*) desc) as seqnum
from t
group by id, diagnosis
) da
where seqnum = 1;