【问题标题】:Create column of second sessions in PySpark在 PySpark 中创建第二个会话列
【发布时间】:2017-02-25 13:38:40
【问题描述】:

在给定以下数据框的情况下,创建显示第二个会话的列的最有效方法是什么:

from pyspark import SparkContext
from pyspark.sql import HiveContext, Window
from pyspark.sql import functions as F

sc = SparkContext("local")
sqlContext = HiveContext(sc)

df = sqlContext.createDataFrame([
    ("u1", "g1", 0),
    ("u2", "g2", 1),
    ("u1", "g2", 2),
    ("u1", "g3", 3),
], ["UserID", "GameID", "Time"])

df.show()

+------+------+----+
|UserID|GameID|Time|
+------+------+----+
|    u1|    g1|   0|
|    u2|    g2|   1|
|    u1|    g2|   2|
|    u1|    g3|   3|
+------+------+----+

期望的输出

如果第一场比赛我也想把时间留作一栏。

+------+------+-----+-----+
|UserID|MinTim|Game1|Game2|
+------+------+-----+-----+
|    u1|     0|   g1|   g2|
|    u1|     2|   g2|   g3|
+------+------+-----+-----+

我曾考虑在 UserID 上使用窗口分区,然后使用 rowsBetween(0, 1),但遇到了问题。

使用 Spark 1.6,但对 2.0 解决方案持开放态度。

【问题讨论】:

标签: apache-spark pyspark apache-spark-sql spark-dataframe pyspark-sql


【解决方案1】:
w = Window().partitionBy("UserID").orderBy(F.col("Time"))

(df
 .select("UserID",
         "Time",
         F.col("GameID").alias("Game1"),
         F.lead("GameID").over(w).alias("Game2"))
 .na.drop(subset="Game2")
).show()

+------+----+-----+-----+
|UserID|Time|Game1|Game2|
+------+----+-----+-----+
|    u1|   0|   g1|   g2|
|    u1|   2|   g2|   g3|
+------+----+-----+-----+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 2018-06-26
    • 2020-12-03
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多