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]))