我有一个数据框如下:
+-----------+------------+-------------+-----------+
| id_doctor | id_patient | consumption | type_drug |
+-----------+------------+-------------+-----------+
| d1 | p1 | 12.0 | bhd |
| d1 | p2 | 10.0 | lsd |
| d1 | p1 | 6.0 | bhd |
| d1 | p1 | 14.0 | carboxyl |
| d2 | p1 | 12.0 | bhd |
| d2 | p1 | 13.0 | bhd |
| d2 | p2 | 12.0 | lsd |
| d2 | p1 | 6.0 | bhd |
| d2 | p2 | 12.0 | bhd |
+-----------+------------+-------------+-----------+
我想统计服用 bhd 的不同患者 < 16.0 for each doctor.
我尝试了以下查询2,但它不起作用:
dataframe.groupBy(col("id_doctor")).agg(
countDistinct(col("id_patient")).where(
col("type_drug") == "bhd" & col("consumption") < 16.0
)
)
PySpark 中的另一个解决方案,无需添加另一列:
dataframe.groupBy("id_doctor").agg(
F.countDistinct(
F.when(
col("type_drug") == "bhd" & col("consumption") < 16.0, col("id_patient")
).otherwise(None)
)
)
只需在数据帧上使用
where
- 此版本删除计数为 0 的 id_doctor :
dataframe.where(
col("type_drug") == "bhd" & col("consumption") < 16.0
).groupBy(
col("id_doctor")
).agg(
countDistinct(col("id_patient"))
)
使用此语法,您可以保留所有“医生”:
dataframe.withColumn(
"fg",
F.when(
(col("type_drug") == "bhd")
& (col("consumption") < 16.0),
col("id_patient")
)
).groupBy(
col("id_doctor")
).agg(
countDistinct(col("fg"))
)
以及无需添加额外列的解决方案(Scala)
dataframe
.groupBy("id_doctor")
.agg(
countDistinct(when(col("type_drug")==="bhd" && col("consumption") < 16.0))
)