代码之家  ›  专栏  ›  技术社区  ›  user3579222

阅读以前的Spark API

  •  0
  • user3579222  · 技术社区  · 5 月前

    在使用以前的Spark版本时,当涉及到指定列名时,我总是感到困惑:我应该使用 String 或a col object .

    示例 regexp_replace from 3.1.2 :

    pyspark.sql.functions.regexp_replace(str,pattern, 替换)[来源]

    我运行了一个3.1.2版本的集群,两者都能正常工作:

    df1.withColumn("modality",F.regexp_replace(F.col("name"),"i","")).display()
    df1.withColumn("modality",F.regexp_replace("name","i","")).display()
    

    从文档中,我假设只允许使用String,但两者都有效。我怎么能在API docu中看到,如果还允许col对象(在最新的API中,这很清楚,但在以前的API中没有)。

    1 回复  |  直到 5 月前
        1
  •  1
  •   Oli    5 月前

    当您点击源按钮时 the 3.1.2 doc 您可以找到的源代码 regexp_replace :

    def regexp_replace(str, pattern, replacement):
        r"""Replace all substrings of the specified string value that match regexp with rep.
    
        .. versionadded:: 1.5.0
    
        Examples
        --------
        >>> df = spark.createDataFrame([('100-200',)], ['str'])
        >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect()
        [Row(d='-----')]
        """
        sc = SparkContext._active_spark_context
        jc = sc._jvm.functions.regexp_replace(_to_java_column(str), pattern, replacement)
        return Column(jc)
    

    你看 str 参数不是直接使用的,而是包含在 _to_java_column 功能。这个 source code of _to_java_column 清楚地表明,它既适用于列名(字符串),也适用于列对象:

    def _to_java_column(col: "ColumnOrName") -> "JavaObject":
        if isinstance(col, Column):
            jcol = col._jc
        elif isinstance(col, str):
            jcol = _create_column_from_name(col)
        else:
            raise PySparkTypeError(
                errorClass="NOT_COLUMN_OR_STR",
                messageParameters={"arg_name": "col", "arg_type": type(col).__name__},
            )
        return jcol
    

    浏览源页面时 functions 你看 _to_java_column 是无所不在的,这意味着对于大多数函数(甚至所有函数,但我没有检查),列对象的两个列名都可以使用。