python - pySpark 替换行子集上的空值

标签 python dataframe pyspark apache-spark-sql null

我有一个 pySpark 数据框,其中有我想要替换的空值 - 但是要替换的值对于不同的组是不同的。

我的数据看起来像这样(抱歉,我没有办法将它作为文本传递):

enter image description here

对于 A 组,我想用 -999 替换空值; 而对于 B 组,我想用 0 替换空值。

目前,我将数据分成几个部分,然后执行 df = df.fillna(-999)

有没有更有效的方法呢?在伪代码中,我在考虑 df = df.where(col('group') == A).fillna(lit(-999)).where(col('group') = = B).fillna(lit(0)) 但当然,这是行不通的。

最佳答案

您可以使用 when :

from pyspark.sql import functions as F

# Loop over all the columns you want to fill
for col in ('Col1', 'Col2', 'Col3'):
    # compute here conditions to fill using a value or another
    fill_a = F.col(col).isNull() & (F.col('Group') == 'A')
    fill_b = F.col(col).isNull() & (F.col('Group') == 'B')

    # Fill the column based on the different conditions 
    # using nested `when` - `otherwise`.
    #
    # Do not forget to add the last `otherwise` with the original 
    # values if none of the previous conditions have been met
    filled_col = (
        F.when(fill_a, -999)
        .otherwise(
            F.when(fill_b, 0)
            .otherwise(F.col(col))
        )
    )

    # 'overwrite' the original column with the filled column
    df = df.withColumn(col, filled_col)

关于python - pySpark 替换行子集上的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74456021/

相关文章:

python - 根据文本语料库中的出现次数列出词汇表中的单词,使用 Scikit-Learn CountVectorizer

Python 正则表达式匹配或标记化

python - 如果文件名中包含字符串,则将值添加到列中(python 3)

python - 无法访问数据框列

python - 使用 pandas.Dataframe 时添加列名删除行

python - 随机森林分类器 - 将索引标签标记转换回字符串值

python - 将整数解析为字符串的意外行为

Python 数据框 : Get alternative days based on month?

numpy - Spark 随机森林 - 无法将 float 转换为 int 错误

apache-spark - spark.table ("TABLE A") 和 spark.read 之间有什么区别。 ("TABLE A")