【问题标题】:How to use the PySpark CountVectorizer on columns that maybe null如何在可能为空的列上使用 PySpark CountVectorizer
【发布时间】:2017-03-14 03:44:10
【问题描述】:

我的 Spark DataFrame 中有一个列:

 |-- topics_A: array (nullable = true)
 |    |-- element: string (containsNull = true)

我正在使用 CountVectorizer:

topic_vectorizer_A = CountVectorizer(inputCol="topics_A", outputCol="topics_vec_A")

我得到 NullPointerExceptions,因为有时 topic_A 列包含 null。

有没有办法解决这个问题?用一个长度为零的数组填充它可以正常工作(尽管它会大大增加数据大小) - 但我不知道如何在 PySpark 中的 Array 列上执行 fillNa。

【问题讨论】:

    标签: apache-spark pyspark apache-spark-mllib


    【解决方案1】:

    我有similar issue,根据评论,我在标记化之前使用了以下语法来解析:

    删除空值

    clean_text_ddf.where(col("title").isNull()).show()
    cleaned_text=clean_text_ddf.na.drop(subset=["title"])
    cleaned_text.where(col("title").isNull()).show()
    cleaned_text.printSchema()
    cleaned_text.show(2)
    
    +-----+
    |title|
    +-----+
    +-----+
    
    +-----+
    |title|
    +-----+
    +-----+
    
    root
     |-- title: string (nullable = true)
    
    +--------------------+
    |               title|
    +--------------------+
    |Mr. Beautiful (Up...|
    |House of Ravens (...|
    +--------------------+
    only showing top 2 rows
    

    【讨论】:

      【解决方案2】:

      我个人会删除带有NULL 值的列,因为那里没有有用的信息,但您可以用空数组替换空值。首先是一些导入:

      from pyspark.sql.functions import when, col, coalesce, array
      

      您可以将特定类型的空数组定义为:

      fill = array().cast("array<string>")
      

      并将其与when 子句结合起来:

      topics_a = when(col("topics_A").isNull(), fill).otherwise(col("topics_A"))
      

      coalesce:

      topics_a = coalesce(col("topics_A"), fill)
      

      并将其用作:

      df.withColumn("topics_A", topics_a)
      

      使用示例数据:

      df = sc.parallelize([(1, ["a", "b"]), (2, None)]).toDF(["id", "topics_A"])
      
      df_ = df.withColumn("topics_A", topics_a)
      topic_vectorizer_A.fit(df_).transform(df_)
      

      结果将是:

      +---+--------+-------------------+
      | id|topics_A|       topics_vec_A|
      +---+--------+-------------------+
      |  1|  [a, b]|(2,[0,1],[1.0,1.0])|
      |  2|      []|          (2,[],[])|
      +---+--------+-------------------+
      

      【讨论】:

        猜你喜欢
        • 2022-08-16
        • 2016-06-16
        • 1970-01-01
        • 2021-01-09
        • 2019-10-26
        • 2022-06-11
        • 1970-01-01
        相关资源
        最近更新 更多