【问题标题】:Shifting slots in a dataframe using pyspark使用 pyspark 移动数据帧中的插槽
【发布时间】:2020-08-21 20:11:54
【问题描述】:

我有一个包含四列的数据框,如下所示,对于每个客户,我有 12 行包含以下详细信息,如示例中所示

Cust_id|slot|trigger_id|coup_type
1|       1| 2101| null
1|       2| 2102| null
1|       3| 2103| null
1|       4| 2104| null
1|       5| 2105| product
1|       6| 2106| null
1|       7| 2107| null
1|       8| 2108| product
1|       9| 2109| null
1|       10| 21010| null
1|       11| 21011| product
1|       12| 21012| product

现在我需要根据 coup_type 执行 slot 移位,这样所有产品 coup 都应该出现在 slot7-10 中,并且分配应该始终从 slot7 开始。移位后的插槽应重新排列如下:-

Cust_id|slot|trigger_id|coup_type
1|       1| 2101| null
1|       2| 2102| null
1|       3| 2103| null
1|       4| 2104| null
1|       5| 2105| null
1|       6| 2106| null
1|       7| 2105| product
1|       8| 2108| product
1|       9| 21011| product
1|       10| 21012| product
1|       11| 21009| null
1|       12| 21010| null

我需要在 pyspark 中执行这个操作。

如果问题不清楚,请告诉我。

提前致谢。

【问题讨论】:

    标签: python pyspark analytics data-analysis data-wrangling


    【解决方案1】:

    您可以通过对列coup_type 进行排序来获得row_number,并将其作为与slot 列的连接键的行号。如果列不连续,那么您可能需要另一列作为slot 列的排序行号。

    from pyspark.sql.functions import *
    from pyspark.sql import Window
    
    w = Window.partitionBy('Cust_id').orderBy(desc('coup_type'))
    
    df2 = df.withColumn('slot', row_number().over(w) + 7 - 1).drop('trigger_id')
    df2.show(12, False)
    
    +-------+----+---------+
    |Cust_id|slot|coup_type|
    +-------+----+---------+
    |1      |7   |product  |
    |1      |8   |product  |
    |1      |9   |product  |
    |1      |10  |product  |
    |1      |11  |null     |
    |1      |12  |null     |
    |1      |13  |null     |
    |1      |14  |null     |
    |1      |15  |null     |
    |1      |16  |null     |
    |1      |17  |null     |
    |1      |18  |null     |
    +-------+----+---------+
    
    df.drop('coup_type').join(df2, ['Cust_id', 'slot'], 'left').show(12, False)
    
    +-------+----+----------+---------+
    |Cust_id|slot|trigger_id|coup_type|
    +-------+----+----------+---------+
    |1      |1   |2101      |null     |
    |1      |2   |2102      |null     |
    |1      |3   |2103      |null     |
    |1      |4   |2104      |null     |
    |1      |5   |2105      |null     |
    |1      |6   |2106      |null     |
    |1      |7   |2107      |product  |
    |1      |8   |2108      |product  |
    |1      |9   |2109      |product  |
    |1      |10  |21010     |product  |
    |1      |11  |21011     |null     |
    |1      |12  |21012     |null     |
    +-------+----+----------+---------+
    

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多