簡體   English   中英

如何在 Pyspark 中替換數據幀的所有空值

[英]How to replace all Null values of a dataframe in Pyspark

我在 pyspark 中有一個超過 300 列的數據框。 在這些列中有一些值為 null 的列。

例如:

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

當我想對 column_1 求和時,結果是 Null,而不是 724。

現在我想用空白替換數據框所有列中的空值。 因此,當我嘗試對這些列求和時,我不會得到空值,但會得到一個數值。

我們如何在 pyspark 中實現這一目標

您可以使用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|
+---+

您可以使用 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|
+---+

使用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()所以它們是相同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM