unpivot列pyspark dataframe,其中value是字典列表

3xiyfsfu  于 2021-07-12  发布在  Spark
关注(0)|答案(1)|浏览(335)

我已经从字典列表中创建了一个pandas数据框架,并使用json\u normalize取消了一列的pivot。现在我必须将代码转换为使用pyspark而不是pandas。

df = pd.json_normalize(list_json,'Messages',['ID'])

ID, Active, Description, Priority
21122, true ,Test description1, 2
21233,true ,Test description1, 2
21233,true ,test2 , 3

在pyspark中,我想不出类似的函数。
我用下面的代码创建了一个Dataframe。但我不知道怎么把它拔出来。

df = spark.sparkContext.parallelize(list_json_messages_tea).map(lambda x: json.dumps(x))
df = spark.read.json(df)

ID, Messages
21122, [{"Active": "true", "Description": "Test description1", "Priority": "2"}]
21233, [{"Active": "true", "Description": "Test description1", "Priority": "2"}, {"Active": "true", "Description": "test2",  "Priority": "3"}]
nlejzf6q

nlejzf6q1#

我相信等价物就是使用 inline(from_json()) :

df2 = df.selectExpr('ID', "inline(from_json(Messages, 'array<struct<Active:string,Description:string,Priority:string>>'))")

df2.show()
+-----+------+-----------------+--------+
|   ID|Active|      Description|Priority|
+-----+------+-----------------+--------+
|21122|  true|Test description1|       2|
|21233|  true|Test description1|       2|
|21233|  true|            test2|       3|
+-----+------+-----------------+--------+

相关问题