【问题标题】:Maximum of minimums in spark Sqlspark Sql中的最大值最小值
【发布时间】:2018-07-08 10:37:42
【问题描述】:

在 Apache Spark 2.0+ 中如何找到最小值的最大值,在以下问题中:

df1
+---+---+
| id| ts|
+---+---+
|  1| 20|
|  2| 15|
+---+---+

df2

+---+---+
| id| ts|
+---+---+
|  1| 10|
|  1| 25|
|  1| 36|
|  2| 25|
|  2| 35|
+---+---+

所需的数据框是:

+---+---+
| id| ts|
+---+---+
|  1| 10|
|  2| 15|
+---+---+

文字问题:对于df1 中的每个id,选择小于df1ts 值的最大ts 值,如果不存在这样的值,只需打印ts 值在df1

【问题讨论】:

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


【解决方案1】:

只需聚合连接并选择 when 否则:

from pyspark.sql.functions import col, when, max as max_

df1 = spark.createDataFrame(
    [(1, 20),(2, 15)], ("id", "ts")
 )
df2 = spark.createDataFrame(
    [(1, 10), (1, 25), (1, 36), (2, 25), (2, 35)], ("id", "ts")
)

ts = when(
    col("df2.ts") < col("df1.ts"), col("df2.ts")
).otherwise(col("df1.ts")).alias("ts")

(df2
    .groupBy("id")
    .agg(max_("ts").alias("ts")).alias("df2")
    .join(df1.alias("df1"), ["id"])
    .select("id", ts)
    .show())

# +---+---+                                                                       
# | id| ts|
# +---+---+
# |  1| 20|
# |  2| 15|
# +---+---+

如果不是所有 id 在df2 中都有等价物,请使用右外连接:

.join(df1.alias("df1"), ["id"], "right")

并将ts调整为

ts = coalesce(when(
    col("df2.ts") < col("df1.ts"), col("df2.ts")
).otherwise(col("df1.ts")), col("df1.ts")).alias("ts")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多