2016-11-10 6 views
1

PySpark DataFrameの小グループ内でどのように操作を行うことができるかを理解しようとしています。私は、次のスキーマを使用したDFを持っていると仮定します。PySpark:DataFrameの小グループ内で反復する

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) 

データは次のようなものになりますので:私はしたいと思います

:各グループ内first_id

  • によって

    1. グループのデータを、 s_id_2で昇順に並べ替えます。
    2. 余分な列layerは、このの順序を示す構造体またはルートのDataFrameに追加しますグループ内の。例えば

    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を有するであろうグループ化。このような問題にどのようにアプローチすればよいでしょうか?

    私は特に、グループ内の列の順序が重要なDataFramesの小グループ(1〜40行)内で反復操作を行う方法に興味があります。

    ありがとうございます!

  • 答えて

    1

    DATAFRAME

    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) 
    

    を作成して、あなたは、あなたがサブグループの順番を示すために、DENSE_RANKウィンドウ機能を使用することができる構造

    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]| 
    +--------+----------+ 
    

    を見ることができます。これは、SQLのパーティションオーバーと同じです。

    ウィンドウ関数の導入:ここ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| 
    +--------+---------+---------------+ 
    
    関連する問題