【问题标题】:PySpark: iterate inside small groups in DataFramePySpark:在 DataFrame 中的小组内迭代
【发布时间】:2016-11-11 10:52:24
【问题描述】:

我试图了解如何在 PySpark DataFrame 中的小组内进行操作。假设我的 DF 具有以下架构:

root
|-- first_id: string (nullable = true)
|-- second_id_struct: struct (nullable = true)
|    |-- s_id: string (nullable = true)
|    |-- s_id_2: int (nullable = true)
|-- depth_from: float (nullable = true)
|-- depth_to: float (nullable = true)
|-- total_depth: float (nullable = true) 

所以数据可能看起来像这样:

我想:

  1. 按 first_id 分组数据
  2. 在每个组内,按 s_id_2 升序排列
  3. 将额外的列layer 附加到结构或根DataFrame 中,以指示此s_id_2 在组中的顺序。

例如:

first_id | second_id | second_id_order 
---------| --------- | ---------------
      A1 |   [B, 10] | 1  
---------| --------- | ---------------
      A1 |   [B, 14] | 2
---------| --------- | ---------------
      A1 |   [B, 22] | 3
---------| --------- | ---------------
      A5 |    [A, 1] | 1
---------| --------- | ---------------
      A5 |    [A, 7] | 2
---------| --------- | ---------------
      A7 |      null | 1
---------| --------- | ---------------        

一旦分组每个first_id 将最多有4 个second_id_struct。我该如何处理这些问题?

我对如何在一般的 DataFrame 小组(1-40 行)内进行迭代操作特别感兴趣,其中组内的列顺序很重要。

谢谢!

【问题讨论】:

    标签: python pyspark grouping spark-dataframe


    【解决方案1】:

    创建一个数据框

    d = [{'first_id': 'A1', 'second_id': ['B',10]}, {'first_id': 'A1', 'second_id': ['B',14]},{'first_id': 'A1', 'second_id': ['B',22]},{'first_id': 'A5', 'second_id': ['A',1]},{'first_id': 'A5', 'second_id': ['A',7]}]
    
    df = sqlContext.createDataFrame(d) 
    

    你可以看到结构

    df.printSchema()
    
    |-- first_id: string (nullable = true)
    |-- second_id: array (nullable = true)
    |........|-- element: string (containsNull = true)
    
    df.show()
    +--------+----------+
    |first_id|second_id |
    +--------+----------+
    |      A1|   [B, 10]|
    |      A1|   [B, 14]|
    |      A1|   [B, 22]|
    |      A5|    [A, 1]|
    |      A5|    [A, 7]|
    +--------+----------+
    

    然后您可以使用 dense_rank 和 Window 函数来显示子组中的顺序。和SQL中的over partition一样。

    窗口功能介绍:Introducing Window Functions in Spark SQL

    代码在这里:

    # setting a window spec
    windowSpec = Window.partitionBy('first_id').orderBy(df.second_id[1])
    # apply dense_rank to the window spec
    df.select(df.first_id, df.second_id, dense_rank().over(windowSpec).alias("second_id_order")).show()
    

    结果:

    +--------+---------+---------------+
    |first_id|second_id|second_id_order|
    +--------+---------+---------------+
    |      A1|  [B, 10]|              1|
    |      A1|  [B, 14]|              2|
    |      A1|  [B, 22]|              3|
    |      A5|   [A, 1]|              1|
    |      A5|   [A, 7]|              2|
    +--------+---------+---------------+
    

    【讨论】:

      猜你喜欢
      • 2022-06-29
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多