使用posexplode分解带有索引的嵌套json

dzhpxtsq  于 2021-05-27  发布在  Spark
关注(0)|答案(4)|浏览(710)

我使用下面的函数来分解一个深度嵌套的json(具有嵌套的结构和数组)。


# Flatten nested df

def flatten_df(nested_df): 

    for col in nested_df.columns:
        array_cols = [c[0] for c in nested_df.dtypes if c[1][:5] == 'array']
    for col in array_cols:
        nested_df =nested_df.withColumn(col, F.explode_outer(nested_df[col]))

    nested_cols = [c[0] for c in nested_df.dtypes if c[1][:6] == 'struct']

    if len(nested_cols) == 0:
        return nested_df

    flat_cols = [c[0] for c in nested_df.dtypes if c[1][:6] != 'struct']

    flat_df = nested_df.select(flat_cols +
                            [F.col(nc+'.'+c).alias(nc+'_'+c)
                                for nc in nested_cols
                                for c in nested_df.select(nc+'.*').columns])

    return flatten_df(flat_df)

我成功地爆炸了。但是我还想在分解的Dataframe中添加元素的顺序或索引。所以在上面的代码中我替换 explode_outer 函数到 posexplode_outer . 但我得到下面的错误

An error was encountered:
'The number of aliases supplied in the AS clause does not match the number of columns output by the UDTF expected 2 aliases'

我试着换衣服 nested_df.withColumnnested_df.select 但我没有成功。有谁能帮我分解嵌套的json,但同时保持数组元素在分解的dataframe中作为列的顺序。

uqjltbpv

uqjltbpv1#

以dataframe格式读取json数据并创建视图或表。在sparksql中,可以使用使用别名引用的number-of-laterviewexplode方法。如果json数据结构是struct类型,那么可以使用点来表示结构。级别1.2

nhaq1z21

nhaq1z212#

错误是因为posexplode\u outer返回两列pos和col,所以不能与column()一起使用。这可以在选择中使用,如下面的代码所示

from pyspark.sql import functions as F
from pyspark.sql.window import Window
tst= sqlContext.createDataFrame([(1,7,80),(1,8,40),(1,5,100),(5,8,90),(7,6,50),(0,3,60)],schema=['col1','col2','col3'])
tst_new = tst.withColumn("arr",F.array(tst.columns))
expr = tst.columns
expr.append(F.posexplode_outer('arr'))

# %%

tst_explode = tst_new.select(*expr)

结果:

tst_explode.show()
+----+----+----+---+---+
|col1|col2|col3|pos|col|
+----+----+----+---+---+
|   1|   7|  80|  0|  1|
|   1|   7|  80|  1|  7|
|   1|   7|  80|  2| 80|
|   1|   8|  40|  0|  1|
|   1|   8|  40|  1|  8|
|   1|   8|  40|  2| 40|
|   1|   5| 100|  0|  1|
|   1|   5| 100|  1|  5|
|   1|   5| 100|  2|100|
|   5|   8|  90|  0|  5|
|   5|   8|  90|  1|  8|
|   5|   8|  90|  2| 90|
|   7|   6|  50|  0|  7|
|   7|   6|  50|  1|  6|
|   7|   6|  50|  2| 50|
|   0|   3|  60|  0|  0|
|   0|   3|  60|  1|  3|
|   0|   3|  60|  2| 60|
+----+----+----+---+---+

如果需要重命名列,可以使用.withcolumnrenamed()函数

df_final=(tst_explode.withColumnRenamed('pos','position')).withColumnRenamed('col','column')
wpcxdonn

wpcxdonn3#

替换 nested_df =nested_df.withColumn(col, F.explode_outer(nested_df[col]))nested_df = df.selectExpr("*", f"posexplode({col}) as (position,col)").drop(col) 您可能需要编写一些逻辑来将列名替换为original,但应该很简单

ddhy6vgd

ddhy6vgd4#

您可以尝试使用列表理解选择来分解现有代码中的arraytype列:

for col in array_cols:
  nested_df = nested_df.select([ F.posexplode_outer(col).alias(col+'_pos', col) if c == col else c for c in nested_df.columns ])

例子:

from pyspark.sql import functions as F

df = spark.createDataFrame([(1,"n1", ["a", "b", "c"]),(2,"n2", ["foo", "bar"])],["id", "name", "vals"])

# +---+----+----------+

# | id|name|      vals|

# +---+----+----------+

# |  1|  n1| [a, b, c]|

# |  2|  n2|[foo, bar]|

# +---+----+----------+

col = "vals" 

df.select([F.posexplode_outer(col).alias(col+'_pos', col) if c == col else c for c in df.columns]).show()

# +---+----+--------+----+

# | id|name|vals_pos|vals|

# +---+----+--------+----+

# |  1|  n1|       0|   a|

# |  1|  n1|       1|   b|

# |  1|  n1|       2|   c|

# |  2|  n2|       0| foo|

# |  2|  n2|       1| bar|

# +---+----+--------+----+

相关问题