如何将每个用户id的第一行的列中的值复制到相同用户id的第二行

5f0d552i  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(391)

我有以下PyparkDataframe:

  1. +-------+---------------------+---+----------+--------------+
  2. |user_id| product | rn|Product_Mo|First_Purchase|
  3. +-------+---------------------+---+----------+--------------+
  4. | 246981|6 month subscription | 1| 6| null|
  5. | 246981|12 month subscription| 2| 12| null|
  6. | 249357|6 month subscription | 1| 6| null|
  7. | 249357|3 month subscription | 2| 3| null|
  8. | 243532|6 month subscription | 1| 6| null|
  9. | 243532|3 month subscription | 2| 3| null|
  10. | 257345|6 month subscription | 1| 6| null|
  11. | 257345|2 month subscription | 2| 2| null|
  12. | 256355|6 month subscription | 1| 6| null|
  13. | 256355|12 month subscription| 2| 12| null|
  14. | 246701|6 month subscription | 1| 6| null|
  15. | 246701|12 month subscription| 2| 12| null|
  16. | 254082|6 month subscription | 1| 6| null|
  17. | 254082|12 month subscription| 2| 12| null|
  18. | 239210|6 month subscription | 1| 6| null|
  19. | 239210|12 month subscription| 2| 12| null|
  20. | 247518|6 month subscription | 1| 6| null|
  21. | 247518|12 month subscription| 2| 12| null|
  22. +-------+---------------------+---+----------+--------------+

我需要捕获产品的值,其中rn=1,并将其复制到第一次购买,其中rn=1和rn=2。这将允许我稍后对第一次购买进行groupby,并计算所有第一次和第二次购买的数量,其中首先购买了6个月的订阅。
生成的Dataframe应如下所示:

  1. +-------+---------------------+---+----------+--------------+
  2. |user_id| product | rn|Product_Mo|First_Purchase|
  3. +-------+---------------------+---+----------+--------------+
  4. | 246981|6 month subscription | 1| 6| 6|
  5. | 246981|12 month subscription| 2| 12| 6|
  6. | 249357|6 month subscription | 1| 6| 6|
  7. | 249357|3 month subscription | 2| 3| 6|
  8. | 243532|6 month subscription | 1| 6| 6|
  9. | 243532|3 month subscription | 2| 3| 6|
  10. | 257345|6 month subscription | 1| 6| 6|
  11. | 257345|2 month subscription | 2| 2| 6|
  12. | 256355|6 month subscription | 1| 6| 6|
  13. | 256355|12 month subscription| 2| 12| 6|
  14. | 246701|6 month subscription | 1| 6| 6|
  15. | 246701|12 month subscription| 2| 12| 6|
  16. | 254082|6 month subscription | 1| 6| 6|
  17. | 254082|12 month subscription| 2| 12| 6|
  18. | 239210|6 month subscription | 1| 6| 6|
  19. | 239210|12 month subscription| 2| 12| 6|
  20. | 247518|6 month subscription | 1| 6| 6|
  21. | 247518|12 month subscription| 2| 12| 6|
  22. +-------+---------------------+---+----------+--------------+

我还没有弄清楚如何在rn=1的情况下获取产品的值,并将其复制到rn=1和rn=2的第一次购买中。其中rn=1的乘积在随后的循环中可能发生变化。所以我需要复制这个值。不会总是6分。
我希望这是有意义的。谢谢你的建议。

m528fe3b

m528fe3b1#

使用 first 作用于 Window 分区依据 user_id 订购方式 rn .

  1. from pyspark.sql import Window
  2. from pyspark.sql.functions import *
  3. w = Window.partitionBy('user_id').orderBy('rn')
  4. df.withColumn('First_Purchase', first('Product_Mo').over(w))

相关问题