【发布时间】:2020-07-06 02:04:46
【问题描述】:
给定如下表格:
+--+------------------+-----------+
|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|
+--+------------------+-----------+
我正在尝试通过对该 id 进行最频繁的诊断来将每个 id 的记录减少到一个。
如果它是一个 rdd,类似的东西会这样做:
rdd.map(lambda x: (x["id"], [(x["diagnosis_age"], x["diagnosis"])]))\
.reduceByKey(lambda x, y: x + y)\
.map(lambda x: [i[1] for i in x[1]])\
.map(lambda x: [max(zip((x.count(i) for i in set(x)), set(x)))])
在 sql 中:
select id, diagnosis, diagnosis_age
from (select id, diagnosis, diagnosis_age, count(*) as cnt,
row_number() over (partition by id order by count(*) desc) as seqnum
from t
group by id, diagnosis, age
) da
where seqnum = 1;
想要的输出:
+--+------------------+-----------+
|id| diagnosis_age| diagnosis|
+--+------------------+-----------+
| 1|2.1843037179180302| 315.320000|
| 2| 5.70572315231258| 315.320000|
| 3| 5.744053881894209| 315.320000|
+--+------------------+-----------+
如果可能,我如何仅使用 spark 数据帧操作来实现相同的效果?特别是不使用任何 rdd 操作/sql。
谢谢
【问题讨论】:
-
如果我错了请纠正我,你想要每个 id 的诊断年龄的最小值和每个 id 的最常见的诊断年龄?
-
@Mohammad Murtaza Hashmi 我只想要每个 id 最频繁的诊断,无论诊断年龄如何,我只是假设在示例表中也会返回最短诊断年龄记录。
-
这能回答你的问题吗? How to select the first row of each group?
标签: dataframe apache-spark pyspark reduce