【问题标题】:PySpark PivotingPySpark 旋转
【发布时间】:2017-10-29 18:54:32
【问题描述】:

我想使用 PySpark 从多个表中透视数据,但我需要以一种奇怪的方式进行。请参阅下面的示例。

原表:

Vehicle_id | Owner_ID    | Vehicle_Buy_Date
--------------------------------------------
1          | 1           | 01/01/2015
1          | 2           | 01/10/2014
2          | 1           | 10/10/2016

最终结果:

Vehicle_id | Owner_1_Buy_Date | Owner_2_Buy_Date
------------------------------------------------
1          |01/01/2015        |01/10/2014
2          |10/10/2016        |NULL

我知道这是一个不寻常的问题,因为这主要不是在数据库表上完成的。

有没有办法在 PySpark 中进行这种类型的旋转?

【问题讨论】:

    标签: python apache-spark pyspark pivot


    【解决方案1】:

    pyspark 中的函数名为pivot

    import pyspark.sql.functions as psf
    df.groupBy("Vehicle_id").pivot("Owner_ID").agg(psf.max("Vehicle_Buy_Date")).show()
    
        +----------+----------+----------+
        |Vehicle_id|         1|         2|
        +----------+----------+----------+
        |         1|01/01/2015|01/10/2014|
        |         2|10/10/2016|      null|
        +----------+----------+----------+
    

    如果您知道不同 Owner_ID 的数量,您可以将其指定为 pivot 函数中的列表参数,否则它将自行计算。

    【讨论】:

      【解决方案2】:

      尝试使用此代码获得所需的结果:

      NewDf = df.withColumn('id', F.concat(F.lit('Owner_'), F.col('owner_id'), F.lit('_Buy_Date')).groupBy('Vehicle_id').pivot('id').agg(F.first('Vehicle_Buy_Date'))
      

      【讨论】:

        【解决方案3】:

        转置你的数据不是一个好主意,很容易reduce你的数据到这样的结构(我这是一个更好的方法):

        Vehicle_id | Owner_ID_Vehicle_Buy_Date_Reduce
        --------------------------------------------
        1          | [{"Owner_ID":1, Vehicle_Buy_Date: 01/01/2015},{ "Owner_ID": 2,   Vehicle_Buy_Date: 01/10/2014}]
        2          | [{"Owner_ID":1, Vehicle_Buy_Date: 10/10/2016}]
        

        你想怎么转置这样的结构?

        Vehicle_id | Owner_ID    | Vehicle_Buy_Date
        --------------------------------------------
        1          | 1           | 01/01/2015
        1          | 2           | 01/10/2014
        1          | 3           | 01/10/2013
        2          | 4           | 10/10/2016
        ...        | ...         | ...
        9          | 123         | 10/10/2017
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-30
          • 2021-03-12
          • 2022-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多