我有一个包含如下数据的表格,
名字 | 价值观 |
---|---|
[a,b,c] | [1,2,3] |
[a,b,c] | [4,5,6] |
如何使用 Spark sql (
SELECT
) 将其转换为下表,而不需要硬编码索引和硬编码列名称?
a | b | c |
---|---|---|
1 | 2 | 3 |
4 | 5 | 6 |
检查下面的代码。
schema = df.selectExpr('''
explode_outer(names) as names
''')
.distinct()
.orderBy("names")
.selectExpr('''
concat_ws(',', transform(collect_list(names), t -> concat(t, ' INT'))) as names
''')
.collect()[0][0]
df \
.selectExpr(f'''
from_json(to_json(map_from_arrays(names, values)), '{schema}') as output
''') \
.selectExpr("output.*") \
.show(10, False)
+---+---+---+
|a |b |c |
+---+---+---+
|1 |2 |3 |
|4 |5 |6 |
+---+---+---+