我有一个具有嵌套结构的 DataFrame(最初是来自 mapreduce 作业的 Avro 输出)。我想把它弄平。原始 DataFrame 的架构如下所示(简化):
|-- key: struct
| |-- outcome: boolean
| |-- date: string
| |-- age: int
| |-- features: map
| | |-- key: string
| | |-- value: double
|-- value: struct (nullable = true)
| |-- nullString: string (nullable = true)
在 Json 表示中,一行数据如下所示:
{"key":
{"outcome": false,
"date": "2015-01-01",
"age" : 20,
"features": {
{"f1": 10.0,
"f2": 11.0,
...
"f100": 20.1
}
},
"value": null
}
features
映射对所有行具有相同的结构,即键集相同(f1、f2、...、f100)。通过“展平“我的意思是以下。
+----------+----------+---+----+----+-...-+------+
| outcome| date|age| f1| f2| ... | f100|
+----------+----------+---+----+----+-...-+------+
| true|2015-01-01| 20|10.0|11.0| ... | 20.1|
...
(truncated)
我正在使用来自 https://github.com/databricks/spark-avro 的 Spark 2.1.0 spark-avro 包.
原始dataframe被读入
import com.databricks.spark.avro._
val df = spark.read.avro("path/to/my/file.avro")
// it's nested
df.show()
+--------------------+------+
| key| value|
+--------------------+------+
|[false,2015... |[null]|
|[false,2015... |[null]|
...
(truncated)
非常感谢任何帮助!
最佳答案
在 Spark 中,您可以从嵌套的 AVRO 文件中提取数据。比如你提供的JSON:
{"key":
{"outcome": false,
"date": "2015",
"features": {
{"f1": v1,
"f2": v2,
...
}
},
"value": null
}
从 AVRO 读取后:
import com.databricks.spark.avro._
val df = spark.read.avro("path/to/my/file.avro")
可以提供来自嵌套 JSON 的扁平化数据。为此,您可以编写如下代码:
df.select("key.*").show
+----+------------+-------+
|date| features |outcome|
+----+------------+-------+
|2015| [v1,v2,...]| false|
+----+------------+-------+
...
(truncated)
df.select("key.*").printSchema
root
|-- date: string (nullable = true)
|-- features: struct (nullable = true)
| |-- f1: string (nullable = true)
| |-- f2: string (nullable = true)
| |-- ...
|-- outcome: boolean (nullable = true)
或者类似这样的东西:
df.select("key.features.*").show
+---+---+---
| f1| f2|...
+---+---+---
| v1| v2|...
+---+---+---
...
(truncated)
df.select("key.features.*").printSchema
root
|-- f1: string (nullable = true)
|-- f2: string (nullable = true)
|-- ...
如果这是您期望的输出。
关于dataframe - 从嵌套结构中提取 Spark 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43332291/