pyspark 中的 first_value 窗口函数 [英] first_value windowing function in pyspark

查看:22
本文介绍了pyspark 中的 first_value 窗口函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pyspark 1.5 从 Hive 表中获取数据并尝试使用窗口函数.

I am using pyspark 1.5 getting my data from Hive tables and trying to use windowing functions.

根据这个 存在一个名为 firstValue 的分析函数,它将为我提供给定窗口的第一个非空值.我知道这存在于 Hive 中,但我无法在 pyspark 的任何地方找到它.

According to this there exists an analytic function called firstValue that will give me the first non-null value for a given window. I know this exists in Hive but I can not find this in pyspark anywhere.

鉴于 pyspark 不允许 UserDefinedAggregateFunctions (UDAF),有没有办法实现这一点?

Is there a way to implement this given that pyspark won't allow UserDefinedAggregateFunctions (UDAFs)?

推荐答案

Spark >= 2.0:

first 接受一个可选的 ignorenulls 参数,它可以模仿 first_value 的行为:

first takes an optional ignorenulls argument which can mimic the behavior of first_value:

df.select(col("k"), first("v", True).over(w).alias("fv"))

火花<2.0:

可用函数被称为 first 可以如下使用:

Available function is called first and can be used as follows:

df = sc.parallelize([
    ("a", None), ("a", 1), ("a", -1), ("b", 3)
]).toDF(["k", "v"])

w = Window().partitionBy("k").orderBy("v")

df.select(col("k"), first("v").over(w).alias("fv"))

但是如果您想忽略空值,则必须直接使用 Hive UDF:

but if you want to ignore nulls you'll have to use Hive UDFs directly:

df.registerTempTable("df")

sqlContext.sql("""
    SELECT k, first_value(v, TRUE) OVER (PARTITION BY k ORDER BY v)
    FROM df""")

这篇关于pyspark 中的 first_value 窗口函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆