sql - 如何根据 PySpark 中的条件进行分组
问题描述
如何根据 PySpark 中的条件进行分组?
这是一个示例数据:
+-----+-------+-------------+------------+
| zip | state | Agegrouping | patient_id |
+-----+-------+-------------+------------+
| 123 | x | Adult | 123 |
| 124 | x | Children | 231 |
| 123 | x | Children | 456 |
| 156 | x | Adult | 453 |
| 124 | y | Adult | 34 |
| 432 | y | Adult | 23 |
| 234 | y | Children | 13 |
| 432 | z | Children | 22 |
| 234 | z | Adult | 44 |
+-----+-------+-------------+------------+
然后想将数据视为:
+-----+-------+-------+----------+------------+
| zip | state | Adult | Children | patient_id |
+-----+-------+-------+----------+------------+
| 123 | x | 1 | 1 | 2 |
| 124 | x | 1 | 1 | 2 |
| 156 | x | 1 | 0 | 1 |
| 432 | y | 1 | 1 | 2 |
| 234 | z | 1 | 1 | 2 |
+-----+-------+-------+----------+------------+
我怎样才能做到这一点?
解决方案
这是火花 sql 版本。
df.createOrReplaceTempView('table')
spark.sql('''
select zip, state,
count(if(Agegrouping = 'Adult', 1, null)) as adult,
count(if(Agegrouping = 'Children', 1, null)) as children,
count(1) as patient_id
from table
group by zip, state;
''').show()
+---+-----+-----+--------+----------+
|zip|state|adult|children|patient_id|
+---+-----+-----+--------+----------+
|123| x| 1| 1| 2|
|156| x| 1| 0| 1|
|234| z| 1| 0| 1|
|432| z| 0| 1| 1|
|234| y| 0| 1| 1|
|124| y| 0| 0| 1|
|124| x| 0| 1| 1|
|432| y| 1| 0| 1|
+---+-----+-----+--------+----------+
推荐阅读
- git - KDiff3 中的 A(基础)、B(本地)、C(远程)与 git 冲突解决程序有什么关系?
- c++ - NPM 安装:找不到平台工具集 = v141
- java - 发布在 Facebook Java Android 上
- json - 用冒号从 Javascript 中的 JSON 对象读取属性
- python - 从多个 Rar 文件中收集评论数据而无需解压缩
- java - 错误 335544421。连接被远程接口拒绝
- c# - 使用 EF Core 加载未映射的属性
- multithreading - 如何同步插入/删除元素到数据结构,功能方式?
- paypal - 字段格式错误:在 payflow pro 中没有 BAID/Account Number/ORIGID 时无法创建 RB Profile
- python - 从宽到长重塑熊猫数据框