gpt4 book ai didi

scala - 如何将 StructType 从 Spark 中的 json 数据帧分解为行而不是列

转载 作者:行者123 更新时间:2023-12-01 09:14:50 25 4
gpt4 key购买 nike

我用这个模式阅读了一个嵌套的json:

 root
|-- company: struct (nullable = true)
| |-- 0: string (nullable = true)
| |-- 1: string (nullable = true)
| |-- 10: string (nullable = true)
| |-- 100: string (nullable = true)
| |-- 101: string (nullable = true)
| |-- 102: string (nullable = true)
| |-- 103: string (nullable = true)
| |-- 104: string (nullable = true)
| |-- 105: string (nullable = true)
| |-- 106: string (nullable = true)
| |-- 107: string (nullable = true)
| |-- 108: string (nullable = true)
| |-- 109: string (nullable = true)

当我尝试:
df.select(col("company.*"))

我将结构“公司”的每个字段都作为列。但我希望它们作为行。我想在另一列中获得带有 id 和字符串的行:
  0        1         10       100      101        102 
"hey" "yooyo" "yuyu" "hey" "yooyo" "yuyu"

而是得到类似的东西:
id    name
0 "hey"
1 "yoooyo"
10 "yuuy"
100 "hey"
101 "yooyo"
102 "yuyu"

在此先感谢您的帮助,

棘手

最佳答案

使用联合试试这个:

val dfExpl = df.select("company.*")

dfExpl.columns
.map(name => dfExpl.select(lit(name),col(name)))
.reduce(_ union _)
.show

或者使用 array/explode :
val dfExpl = df.select("company.*")
val selectExpr = dfExpl
.columns
.map(name =>
struct(
lit(name).as("id"),
col(name).as("value")
).as("col")
)


dfExpl
.select(
explode(array(selectExpr: _*))
)
.select("col.*")
.show()

关于scala - 如何将 StructType 从 Spark 中的 json 数据帧分解为行而不是列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47418971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com