【问题标题】:probnorm function equivalent in pysparkpyspark中的probnorm函数等效
【发布时间】:2021-08-03 23:07:35
【问题描述】:

PROBNORM:解释

SAS 中的 PROBNORM 函数返回标准正态分布的观测值小于或等于 x 的概率。

pyspark中是否有等价的功能?

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql sas


    【解决方案1】:

    恐怕在 PySpark 中没有这样的实现方法。
    但是,您可以利用Pandas UDFs 使用基本的 Python 包定义您自己的自定义函数!在这里,我们将使用scipy.stats.norm 模块从标准正态分布中获取累积概率。

    我正在使用的版本:

    • Spark 3.1.1
    • pandas 1.1.5
    • scipy 1.5.2

    示例代码

    import pandas as pd
    from scipy.stats import norm
    import pyspark.sql.functions as F
    from pyspark.sql.functions import pandas_udf
    
    
    # create sample data
    df = spark.createDataFrame([
        (1, 0.00),
        (2, -1.23),
        (3, 4.56),
    ], ['id', 'value'])
    
    
    # define your custom Pandas UDF
    @pandas_udf('double')
    def probnorm(s: pd.Series) -> pd.Series:
        return pd.Series(norm.cdf(s))
    
    
    # create a new column using the Pandas UDF
    df = df.withColumn('pnorm', probnorm(F.col('value')))
    
    
    df.show()
    
    +---+-----+-------------------+
    | id|value|              pnorm|
    +---+-----+-------------------+
    |  1|  0.0|                0.5|
    |  2|-1.23|0.10934855242569191|
    |  3| 4.56| 0.9999974423189606|
    +---+-----+-------------------+
    

    编辑

    如果您的工作器上也没有正确安装 scipy,您可以使用 Python 基础包 math 和一点点 statistics knowledge

    import math
    from pyspark.sql.functions import udf
    
    def normal_cdf(x, mu=0, sigma=1):
        """
        Cumulative distribution function for the normal distribution
        with mean `mu` and standard deviation `sigma`
        """
        return (1 + math.erf((x - mu) / (sigma * math.sqrt(2)))) / 2
    
    my_udf = udf(normal_cdf)
    
    df = df.withColumn('pnorm', my_udf(F.col('value')))
    
    df.show()
    
    +---+-----+-------------------+
    | id|value|              pnorm|
    +---+-----+-------------------+
    |  1|  0.0|                0.5|
    |  2|-1.23|0.10934855242569197|
    |  3| 4.56| 0.9999974423189606|
    +---+-----+-------------------+
    

    结果其实是一样的。

    【讨论】:

    • 我收到错误消息:ImportError: PyArrow >= 0.8.0 must be installed;...有什么方法可以使 ppf 功能正常工作,因为我没有安装 pyArrow 的权限
    • 你可以试试,虽然我不是很自信:norm_cdf = F.udf(lambda x: float(norm.cdf(x))); df = df.withColumn('pnorm', norm_cdf(F.col('value')))
    • 仍然没有运气:Py4JJavaError:调用 o1689.showString 时发生错误。 ModuleNotFoundError:没有名为“scipy”的模块
    • def probnorm(s: pd.Series) -> pd.Series: return pd.Series(norm.cdf(s)) 这部分会抛出 PyArrow 错误...如果我只使用 norm_cdf = F .udf(lambda x: float(norm.cdf(x))) 我得到 scipy 错误
    • 我有 scipy 1.2 版
    猜你喜欢
    • 2022-11-03
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    相关资源
    最近更新 更多