PySpark 2.2 爆炸删除空行(如何实现explode_outer)?

Ale*_*der 2 python apache-spark apache-spark-sql pyspark

我正在 PySpark 数据框中处理一些深度嵌套的数据。当我尝试将结构展平为行和列时,我注意到当我调用withColumn该行是否包含null在源列中时,该行将从我的结果数据框中删除。相反,我想找到一种方法来保留该行并null在结果列中包含该行。

要使用的示例数据框:

from pyspark.sql.functions import explode, first, col, monotonically_increasing_id
from pyspark.sql import Row

df = spark.createDataFrame([
  Row(dataCells=[Row(posx=0, posy=1, posz=.5, value=1.5, shape=[Row(_type='square', _len=1)]), 
                 Row(posx=1, posy=3, posz=.5, value=4.5, shape=[]), 
                 Row(posx=2, posy=5, posz=.5, value=7.5, shape=[Row(_type='circle', _len=.5)])
    ])
])
Run Code Online (Sandbox Code Playgroud)

我还有一个用于扁平结构的函数:

def flatten_struct_cols(df):
    flat_cols = [column[0] for column in df.dtypes if 'struct' not in column[1][:6]]
    struct_columns = [column[0] for column in df.dtypes if 'struct' in column[1][:6]]

    df = df.select(flat_cols +
                   [col(sc + '.' + c).alias(sc + '_' + c)
                   for sc in struct_columns
                   for c in df.select(sc + '.*').columns])

    return df
Run Code Online (Sandbox Code Playgroud)

架构如下所示:

df.printSchema()

root
 |-- dataCells: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- posx: long (nullable = true)
 |    |    |-- posy: long (nullable = true)
 |    |    |-- posz: double (nullable = true)
 |    |    |-- shape: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- _len: long (nullable = true)
 |    |    |    |    |-- _type: string (nullable = true)
 |    |    |-- value: double (nullable = true)
Run Code Online (Sandbox Code Playgroud)

起始数据框:

df.show(3)

+--------------------+
|           dataCells|
+--------------------+
|[[0,1,0.5,Wrapped...|
+--------------------+
Run Code Online (Sandbox Code Playgroud)

我首先分解数组,因为我想将这个结构数组和结构数组转换为行和列。然后我将结构字段展平为新列。

df = df.withColumn('dataCells', explode(col('dataCells')))
df = flatten_struct_cols(df)
df.show(3)
Run Code Online (Sandbox Code Playgroud)

我的数据看起来像:

+--------------+--------------+--------------+---------------+---------------+
|dataCells_posx|dataCells_posy|dataCells_posz|dataCells_shape|dataCells_value|
+--------------+--------------+--------------+---------------+---------------+
|             0|             1|           0.5|   [[1,square]]|            1.5|
|             1|             3|           0.5|             []|            4.5|
|             2|             5|           0.5|[[null,circle]]|            7.5|
+--------------+--------------+--------------+---------------+---------------+
Run Code Online (Sandbox Code Playgroud)

一切都很好,正如预期的那样,直到我尝试使用具有空/空值explodedataCells_shape列。

df = df.withColumn('dataCells_shape', explode(col('dataCells_shape')))
df.show(3)
Run Code Online (Sandbox Code Playgroud)

这将第二行从数据框中删除:

+--------------+--------------+--------------+---------------+---------------+
|dataCells_posx|dataCells_posy|dataCells_posz|dataCells_shape|dataCells_value|
+--------------+--------------+--------------+---------------+---------------+
|             0|             1|           0.5|     [1,square]|            1.5|
|             2|             5|           0.5|  [null,circle]|            7.5|
+--------------+--------------+--------------+---------------+---------------+
Run Code Online (Sandbox Code Playgroud)

相反,我想保留该行并保留该列的空值以及其他列中的所有值。我尝试创建一个新列,而不是在执行该操作时覆盖旧列,.withColumn explode并以任何一种方式获得相同的结果。

如果行不为空/空,我还尝试创建一个UDF执行该explode函数的函数,但是我遇到了 JVM 错误处理null

from pyspark.sql.functions import udf
from pyspark.sql.types import NullType, StructType

def explode_if_not_null(trow):
    if trow:
        return explode(trow)
    else:
        return NullType

func_udf = udf(explode_if_not_null, StructType())
df = df.withColumn('dataCells_shape_test', func_udf(df['dataCells_shape']))
df.show(3)

AttributeError: 'NoneType' object has no attribute '_jvm'
Run Code Online (Sandbox Code Playgroud)

任何人都可以为我建议一种方法来爆炸或展ArrayType平列而不会丢失列时的行null吗?

我正在使用 PySpark 2.2.0

编辑:

按照作为可能的欺骗提供的链接,我尝试实施.isNotNull().otherwise()提供结构模式的建议解决方案,.otherwise但该行仍然从结果集中退出。

df.withColumn("dataCells_shape_test", explode(when(col("dataCells_shape").isNotNull(), col("dataCells_shape"))
                                              .otherwise(array(lit(None).cast(df.select(col("dataCells_shape").getItem(0))
                                                                                                              .dtypes[0][1])
                                                              )
                                                        )
                                             )
             ).show()

+--------------+--------------+--------------+---------------+---------------+--------------------+
|dataCells_posx|dataCells_posy|dataCells_posz|dataCells_shape|dataCells_value|dataCells_shape_test|
+--------------+--------------+--------------+---------------+---------------+--------------------+
|             0|             1|           0.5|   [[1,square]]|            1.5|          [1,square]|
|             2|             5|           0.5|[[null,circle]]|            7.5|       [null,circle]|
+--------------+--------------+--------------+---------------+---------------+--------------------+
Run Code Online (Sandbox Code Playgroud)

Ale*_*der 5

感谢pault向我指出这个问题这个关于将 Python 映射到 Java 的问题。我能够得到一个有效的解决方案:

from pyspark.sql.column import Column, _to_java_column

def explode_outer(col):
    _explode_outer = sc._jvm.org.apache.spark.sql.functions.explode_outer 
    return Column(_explode_outer(_to_java_column(col)))

new_df = df.withColumn("dataCells_shape", explode_outer(col("dataCells_shape")))

+--------------+--------------+--------------+---------------+---------------+
|dataCells_posx|dataCells_posy|dataCells_posz|dataCells_shape|dataCells_value|
+--------------+--------------+--------------+---------------+---------------+
|             0|             1|           0.5|     [1,square]|            1.5|
|             1|             3|           0.5|           null|            4.5|
|             2|             5|           0.5|  [null,circle]|            7.5|
+--------------+--------------+--------------+---------------+---------------+

root
 |-- dataCells_posx: long (nullable = true)
 |-- dataCells_posy: long (nullable = true)
 |-- dataCells_posz: double (nullable = true)
 |-- dataCells_shape: struct (nullable = true)
 |    |-- _len: long (nullable = true)
 |    |-- _type: string (nullable = true)
 |-- dataCells_value: double (nullable = true)
Run Code Online (Sandbox Code Playgroud)

重要的是要注意,这适用于 pyspark 2.2 版,因为它explode_outer 在 spark 2.2 中定义的(但由于某种原因,直到 2.3 版才在 pyspark 中实现 API 包装器)。此解决方案为已实现的 java 函数创建了一个包装器。