【问题标题】:Split Dataframe to Dict of Dataframe using pyspark使用 pyspark 将数据框拆分为数据框的字典
【发布时间】:2020-06-11 05:46:44
【问题描述】:

我有如下数据框

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 将数据帧组的 dict 拆分为某列

{ "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

但我正在寻找其他更快的方法

【问题讨论】:

  • 在 pandas 中你可以使用 {k:v for k,v in df.groupby('Key')} 也许它在 pyspark 中是一样的
  • 您想要实现的是 {key,dataframe} 的 dict,这不是 spark 的最佳策略?

标签: python pandas pyspark


【解决方案1】:

即使代码 scala 中的函数在 Scala 和 PySpark 中是相同的

  • Key分组
  • 创建一个map,其中键是Key,值是结构列表 这可以使用

    来实现

    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)
  }

}

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 2019-04-03
    • 2022-08-21
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多