python - 使用 pyspark 将数据框拆分为数据框的字典
问题描述
我有如下数据框
id | Key | Value |
-----------------------
0 | Key1 | 100 |
1 | Key1 | 101 |
2 | Key1 | 102 |
3 | Key1 | 103 |
4 | Key2 | 104 |
5 | Key2 | 105 |
6 | Key2 | 106 |
7 | Key3 | 107 |
8 | Key3 | 108 |
9 | Key3 | 109 |
我想通过使用 pyspark 将某些列拆分为数据帧组的字典,如下所示
{ "Key1" : id | Key | Value |
-----------------------
0 | Key1 | 100 |
1 | Key1 | 101 |
2 | Key1 | 102 |
3 | Key1 | 103 |,
"Key2" : id | Key | Value |
-----------------------
4 | Key2 | 104 |
5 | Key2 | 105 |
6 | Key2 | 106 |,
"Key3" : id | Key | Value |
-----------------------
7 | Key3 | 107 |
8 | Key3 | 108 |
9 | Key3 | 109 | }
我正在使用带有 pyspark 的 spark 2.7.1。
我已经尝试过了
out = dict()
for i in ["Key1", "Key2","Key3"]:
out[i] = df.where(df.key == i)
return out
但我正在寻找其他更快的方式
解决方案
即使代码 scala 中的函数在 Scala 和 PySpark 中是相同的
- 通过...分组
Key
创建一个
map
where key isKey
and value is List of Struct 这可以使用来实现df.groupBy("Key") .agg( map(col("Key"),collect_list( struct(col("id"),col("Key"),col("Values")) )) .as("outputMap")) .show(false)
import org.apache.spark.sql.functions._
object GroupColumns {
def main(args: Array[String]): Unit = {
val spark = Constant.getSparkSess
import spark.implicits._
val df = List( (0,"Key1",100),(1,"Key1",101),(2,"Key1",102),(3,"Key1",103),
(0,"Key2",100),(1,"Key2",101),(2,"Key2",102),(3,"Key2",103)).toDF("id","Key","Values")
// df.show()
df.groupBy("Key")
.agg(
map(col("Key"),collect_list( struct(col("id"),col("Key"),col("Values")) ))
.as("outputMap"))
.drop("Key")
.show(false)
}
}
推荐阅读
- java - 在 Pramp 中无法识别 System.out.println?
- apache-kafka - 可以在 AVRO 模式中扩展 ENUM
- html - 编辑后如何修复导航栏,现在移动版本不起作用?
- node.js - nodejs将blob(base64)作为图像提供
- javascript - 将 ES 模块导入全局范围?
- reactjs - 如何在 React 中基于 dom 更新我的组件
- python - Python使用正则表达式转换字符串
- multithreading - 交互式线程和非交互式线程有什么区别?以及不同CPU调度器的性能?
- c++ - 我如何使用
> 在 C++ 中? - machine-learning - 使用 PyTorch 训练多类 CNN 时,损失非常大