Python 我只需要在pyspark dataframe中附加那些具有非空值的对象
我使用的pyspark数据帧(df)具有以下示例表(表1): id,col1,col2,col3 1,abc,null,def 2,空,定义,abc 3,def,abc,空 我试图通过忽略空值来添加所有列,从而获得新列(final)。 我尝试过pyspark代码并使用了f.array(col1、col2、col3)。正在追加值,但不会忽略空值。我还尝试过UDF只附加非空列,但它不起作用Python 我只需要在pyspark dataframe中附加那些具有非空值的对象,python,arrays,pyspark,apache-spark-sql,pyspark-sql,Python,Arrays,Pyspark,Apache Spark Sql,Pyspark Sql,我使用的pyspark数据帧(df)具有以下示例表(表1): id,col1,col2,col3 1,abc,null,def 2,空,定义,abc 3,def,abc,空 我试图通过忽略空值来添加所有列,从而获得新列(final)。 我尝试过pyspark代码并使用了f.array(col1、col2、col3)。正在追加值,但不会忽略空值。我还尝试过UDF只附加非空列,但它不起作用 import pyspark.sql.functions as f df = spark.table(
import pyspark.sql.functions as f
df = spark.table('table1')
df = df.withColumn('final', f.array(col1,col2,col3))
Actual result:
id, col1, col2, col3, final
1, abc, null, def, [abc,,def]
2, null, def, abc, [,def, abc]
3, def, abc, null, [def,abc,,]
expected result:
id, col1, col2, col3, final
1, abc, null, def, [abc,def]
2, null, def, abc, [def, abc]
3, def, abc, null, [def,abc]
my col1, col2, col3 schema are as below:
where as col1 name is applications
applications: struct (nullable = false)
applicationid: string (nullable = true)
createdat: string (nullable = true)
updatedat: string (nullable = true)
source_name: string (nullable = true)
status: string (nullable = true)
creditbureautypeid: string (nullable = true)
score: integer (nullable = true)
applicationcreditreportid: string (nullable = true)
firstname: string (nullable = false)
lastname: string (nullable = false)
dateofbirth: string (nullable = false)
accounts: array (nullable = true)
element: struct (containsNull = true)
applicationcreditreportaccountid: string (nullable = true)
currentbalance: integer (nullable = true)
institutionid: string (nullable = true)
accounttypeid: string (nullable = true)
dayspastdue: integer (nullable = true)
institution_name: string (nullable = true)
account_type_name: string (nullable = true)
如果问题不清楚或需要更多信息,请告诉我。
任何帮助都将不胜感激。:) 您可以定义自己的
UDF
如下:
def only_not_null(st,nd,rd):
return [x for x in locals().values() if x is not None] # Take non empty columns
然后打电话:
df = spark.table('table1')
df = df.withColumn('final', f.udf(only_not_null)(col1,col2,col3))
使用自定义项
from pyspark.sql.functions import udf, array
def join_columns(row_list):
return [cell_val for cell_val in row_list if cell_val is not None]
join_udf = udf(join_columns)
df = spark.table('table1')
df = df.withColumn('final', join_udf(array(col1,col2,col3))
不仅适用于3列,还可以编辑阵列中的列。由于Spark 2.4,您可以使用更高阶的函数来实现这一点(不需要自定义项)。在PySpark中,查询可以如下所示:
result = (
df
.withColumn("temp", f.array("col1", "col2", "col3"))
.withColumn("final", f.expr("FILTER(temp, x -> x is not null)"))
.drop("temp")
)
为什么要使用
locals().values()
?如果x不正确,也要使用,因为这会过滤掉任何虚假的值,如0
或”
。实际上,pyspark的版本可能不会有什么不同:感谢您的回复!但是,我的列模式很复杂。我以字符串列为例。当我定义函数时,我还必须给出返回类型。我提到了我的专栏模式。太好了@David。它的工作:)我尝试了多种解决方案,但这就像一个魅力。谢谢