使用pyspark移动数据帧中的插槽

2024-05-23 22:17:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,有四列,如下所示,对于每个客户,我有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_类型执行插槽移动,这样所有产品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中执行此操作

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

提前谢谢


Tags: id类型dataframe客户产品type详细信息product
1条回答
网友
1楼 · 发布于 2024-05-23 22:17:25

您可以通过对列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     |
+   -+  +     +    -+

相关问题 更多 >