Pyspark:用数据框中的空值替换所有出现的值

时间:2020-06-29 15:45:57

标签: apache-spark pyspark apache-spark-sql pyspark-dataframes

我有一个类似于以下的数据框。我最初用-1填充所有空值以在Pyspark中进行联接。

df = pd.DataFrame({'Number': ['1', '2', '-1', '-1'],
                   'Letter': ['A', '-1', 'B', 'A'],
                   'Value': [30, 30, 30, -1]})


pyspark_df = spark.createDataFrame(df)

+------+------+-----+
|Number|Letter|Value|
+------+------+-----+
|     1|     A|   30|
|     2|    -1|   30|
|    -1|     B|   30|
|    -1|     A|   -1|
+------+------+-----+

处理完数据集后,我需要将所有-1都替换为空值。

+------+------+-----+
|Number|Letter|Value|
+------+------+-----+
|     1|     A|   30|
|     2|  null|   30|
|  null|     B|   30|
|  null|     A| null|
+------+------+-----+

最简单的方法是什么?

4 个答案:

答案 0 :(得分:8)

另一种不太繁琐的方法是使用 replace

pyspark_df.replace(-1,None).replace('-1',None).show()

答案 1 :(得分:5)

when+otherwise将达到目的:

import pyspark.sql.functions as F

pyspark_df.select([F.when(F.col(i).cast("Integer") <0 , None).otherwise(F.col(i)).alias(i)
                  for i in df.columns]).show()

+------+------+-----+
|Number|Letter|Value|
+------+------+-----+
|     1|     A|   30|
|     2|  null|   30|
|  null|     B|   30|
|  null|     A| null|
+------+------+-----+

答案 2 :(得分:3)

您可以扫描所有列,并将-1替换为None:

import pyspark.sql.functions as F

for x in pyspark_df.columns:
    pyspark_df = pyspark_df.withColumn(x, F.when(F.col(x)==-1, F.lit(None)).otherwise(F.col(x)))

pyspark_df.show()

输出:

+------+------+-----+
|Number|Letter|Value|
+------+------+-----+
|     1|     A|   30|
|     2|  null|   30|
|  null|     B|   30|
|  null|     A| null|
+------+------+-----+

答案 3 :(得分:2)

使用 reduce when+otherwise 应用于数据框的所有列。

df.show()
#+------+------+-----+
#|Number|Letter|Value|
#+------+------+-----+
#|     1|     A|   30|
#|     2|    -1|   30|
#|    -1|     B|   30|
#+------+------+-----+
from functools import reduce

(reduce(lambda new_df, col_name: new_df.withColumn(col_name, when(col(col_name)== '-1',lit(None)).otherwise(col(col_name))),df.columns,df)).show()
#+------+------+-----+
#|Number|Letter|Value|
#+------+------+-----+
#|     1|     A|   30|
#|     2|  null|   30|
#|  null|     B|   30|
#+------+------+-----+