Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在单独的组中存储列并保留空值_Python_Pyspark_Pyspark Sql_Pyspark Dataframes - Fatal编程技术网

Python 如何在单独的组中存储列并保留空值

Python 如何在单独的组中存储列并保留空值,python,pyspark,pyspark-sql,pyspark-dataframes,Python,Pyspark,Pyspark Sql,Pyspark Dataframes,我有一个带有连续变量的列,想将其存储起来进行绘图。但是,此列也包含空值 我使用以下代码将其装箱: defa(b): 如果b您可以在不使用udf的情况下执行此操作。下面是重写代码的一种方法,它为null值提供了一个特殊的存储桶: from pyspark.sql.functions import col, when def a(b): return when(b.isNull(), "Other")\ .when(b <= 20, "<= 20")\

我有一个带有连续变量的列,想将其存储起来进行绘图。但是,此列也包含空值

我使用以下代码将其装箱:

defa(b):

如果b您可以在不使用
udf
的情况下执行此操作。下面是重写代码的一种方法,它为
null
值提供了一个特殊的存储桶:

from pyspark.sql.functions import col, when

def a(b):
    return when(b.isNull(), "Other")\
        .when(b <= 20, "<= 20")\
        .when(b <= 40, "20 < <= 40")\
        .when(b <= 45, "40 < <= 45")\
        .otherwise("> 45")

data = data.withColumn("a_bucket", a(col("b")))
从pyspark.sql.functions导入col,当
def a(b):
当(b.isNull(),“其他”)时返回\

.when(b)如果b为None,则放入
:在
udf
顶部返回“OTHER”
,但无需
udf
即可轻松完成此操作。
from functools import reduce

def aNew(b, buckets):
    """assumes buckets are sorted"""
    if not buckets:
        raise ValueError("buckets can not be empty")
    return reduce(
        lambda w, i: w.when(
            b.between(buckets[i-1], buckets[i]), 
            "{low} < <= {high}".format(low=buckets[i-1], high=buckets[i]))
        ),
        range(1, len(buckets)),
        when(
            b.isNull(), 
            "Other"
        ).when(
            b <= buckets[0], 
            "<= {first}".format(first=buckets[0])
        )
    ).otherwise("> {last}".format(last=buckets[-1]))

data = data.withColumn("a_bucket", aNew(col("b"), buckets=[20, 40, 45]))