【问题标题】:How to replace all Null values of a dataframe in Pyspark如何在 Pyspark 中替换数据框的所有 Null 值
【发布时间】:2017-07-07 19:30:22
【问题描述】:

我在 pyspark 中有一个包含 300 多列的数据框。在这些列中,有些列的值为 null。

例如:

Column_1 column_2
null     null
null     null
234      null
125      124
365      187
and so on

当我想对 column_1 求和时,结果是 Null,而不是 724。

现在我想用空白空间替换数据框所有列中的 null。因此,当我尝试对这些列求和时,我不会得到空值,但会得到一个数值。

我们如何在 pyspark 中实现这一点

【问题讨论】:

    标签: dataframe null pyspark


    【解决方案1】:

    使用 fillna 有 3 个选项...

    文档:

    def fillna(self, value, subset=None):
       """Replace null values, alias for ``na.fill()``.
       :func:`DataFrame.fillna` and :func:`DataFrameNaFunctions.fill` are aliases of each other.
    
       :param value: int, long, float, string, bool or dict.
           Value to replace null values with.
           If the value is a dict, then `subset` is ignored and `value` must be a mapping
           from column name (string) to replacement value. The replacement value must be
           an int, long, float, boolean, or string.
       :param subset: optional list of column names to consider.
           Columns specified in subset that do not have matching data type are ignored.
           For example, if `value` is a string, and subset contains a non-string column,
           then the non-string column is simply ignored.
    

    所以你可以:

    1. 用相同的值填充所有列:df.fillna(value)
    2. 传递列的字典 --> 值:df.fillna(dict_of_col_to_value)
    3. 传递要填充相同值的列列表:df.fillna(value, subset=list_of_cols)

    fillna()na.fill() 的别名,所以它们是相同的。

    【讨论】:

      【解决方案2】:

      你可以使用 fillna() 函数。

      >>> df = spark.createDataFrame([(1,), (2,), (3,), (None,)], ['col'])
      >>> df.show()
      +----+
      | col|
      +----+
      |   1|
      |   2|
      |   3|
      |null|
      +----+
      
      >>> df = df.fillna({'col':'4'})
      >>> df.show()
      
      or df.fillna({'col':'4'}).show()
      
      +---+
      |col|
      +---+
      |  1|
      |  2|
      |  3|
      |  4|
      +---+
      

      【讨论】:

      • 首选此函数,因为您可以指定要使用的列,谢谢。
      • 这也是首选,因为您可以将其分配给相同或另一个数据框。
      【解决方案3】:

      您可以使用df.na.fill 将空值替换为零,例如:

      >>> df = spark.createDataFrame([(1,), (2,), (3,), (None,)], ['col'])
      >>> df.show()
      +----+
      | col|
      +----+
      |   1|
      |   2|
      |   3|
      |null|
      +----+
      
      >>> df.na.fill(0).show()
      +---+
      |col|
      +---+
      |  1|
      |  2|
      |  3|
      |  0|
      +---+
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-21
        • 1970-01-01
        • 2019-07-24
        • 2018-03-09
        • 1970-01-01
        • 1970-01-01
        • 2019-04-28
        相关资源
        最近更新 更多