在pyspark中合并对象数组

时间:2018-11-17 19:32:19

标签: pyspark apache-spark-sql

请考虑以下DF:

df = spark.createDataFrame(
    [
        Row(
            x='a',
            y=[
                {'f1': 1, 'f2': 2},
                {'f1': 3, 'f2': 4}
            ],
            z=[
                {'f3': 1, 'f4': '2'},
                {'f3': 1, 'f4': '4', 'f5': [1,2,3]}
            ]
        )
    ]
)

我希望按索引方式组合y和z,所以我可能会得到:

[
    Row(x='a', y={'f1': 1, 'f2': 2}, z={'f3': 1, 'f4': 2}), 
    Row(x='a', y={'f1': 3, 'f2': 4}, z={'f3': 1, 'f4': 4, 'f5': [1,2,3]})
]

不转换为rdd怎么办?

1 个答案:

答案 0 :(得分:0)

这是输出,与您的预期有点不同:z列的值更改为string,无论是int,string还是list。

[Row(x='a', y={'f2': 2, 'f1': 1}, z={'f3': '1', 'f4': '2'}), Row(x='a', y={'f2': 4, 'f1': 3}, z={'f3': '1', 'f4': '4', 'f5': '[1, 2, 3]'})]

这是输出

   from pyspark.sql import Row
   from pyspark.sql.types import *
   from pyspark.sql.functions import explode,monotonically_increasing_id

   df = spark.createDataFrame(<br>[Row(x='a',y=[{'f1': 1, 'f2': 2}, {'f1': 3, 'f2': 4}],z=[{'f3': 1, 'f4': '2'}, {'f3': 1, 'f4': '4', 'f5': [1,2,3]}])]
  ,StructType([StructField('x', StringType(), True),
   StructField('y', ArrayType(MapType(StringType(), IntegerType(), True), True),True),
   StructField('z', ArrayType(MapType(StringType(), StringType(), True), True),True)]))
df1 = df.select('x',explode(df.y).alias("y")).withColumn("id", monotonically_increasing_id())
df2 = df.select(explode(df.z).alias("z")).withColumn("id", monotonically_increasing_id())
df3 = df1.join(df2, "id", "outer").drop("id")
df3.collect()

来自代码

{{1}}