我有一個具有以下架構的資料框:
root
|-- id: long (nullable = true)
|-- type: string (nullable = true)
|-- tags: map (nullable = true)
| |-- key: string
| |-- value: string (valueContainsNull = true)
|-- lat: Long (nullable = true)
|-- lon: Long (nullable = true)
|-- nds: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- ref: long (nullable = true)
|-- members: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- type: string (nullable = true)
| | |-- ref: long (nullable = true)
| | |-- role: string (nullable = true)
我想創建一個新的資料框res,在其中從列中選擇特定資料tags。我需要valuesfromkey=place和key=population. 新資料框應具有以下架構:
val schema = StructType(
Array(
StructField("place", StringType),
StructField("population", LongType)
)
)
我完全不知道該怎么做。我試圖復制第一個資料框,然后選擇列,但這沒有用。
有人有解決方案嗎?
uj5u.com熱心網友回復:
讓我們呼叫您的原始資料框df。你可以像這樣提取你想要的資訊
import org.apache.spark.sql.functions.sql.col
val data = df
.select("tags")
.where(
df("tags")("key") isin (List("place", "population"): _*)
)
.select(
col("tags")("value")
)
.collect()
.toList
這將為您提供一個List[Row]可以使用您的架構轉換為另一個資料框的資料框
import scala.collection.JavaConversions.seqAsJavaList
sparkSession.createDataFrame(seqAsJavaList[Row](data), schema)
uj5u.com熱心網友回復:
給定以下簡化輸入:
val df = Seq(
(1L, Map("place" -> "home", "population" -> "1", "name" -> "foo")),
(2L, Map("place" -> "home", "population" -> "4", "name" -> "foo")),
(3L, Map("population" -> "3")),
(4L, Map.empty[String, String])
).toDF("id", "tags")
您想使用方法來選擇值map_filter以過濾地圖以僅包含您想要的鍵,然后呼叫map_values以獲取這些條目。map_values回傳一個陣列,因此您需要使用它explode_outer來展平資料。我們explode_outer在這里使用是因為您可能有既沒有地點也沒有人口的條目,或者只有兩者之一。一旦資料形成我們可以輕松使用的表單,我們只需在所需結構中選擇我們想要的欄位。
我已經將id列留在了,所以當您運行示例時,您可以看到我們不會洗掉缺少資料的條目。
val r = df.select(
col("id"),
explode_outer(map_values(map_filter(col("tags"), (k,_) => k === "place"))) as "place",
map_values(map_filter(col("tags"), (k,_) => k === "population")) as "population"
).withColumn("population", explode_outer(col("population")))
.select(
col("id"),
array(
struct(
col("place"),
col("population") cast LongType as "population"
) as "place_and_population"
) as "data"
)
給出:
root
|-- id: long (nullable = false)
|-- data: array (nullable = false)
| |-- element: struct (containsNull = false)
| | |-- place: string (nullable = true)
| | |-- population: long (nullable = true)
--- --------------
| id| data|
--- --------------
| 1| [{home, 1}]|
| 2| [{home, 4}]|
| 3| [{null, 3}]|
| 4|[{null, null}]|
--- --------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322865.html
標籤:爪哇 斯卡拉 数据框 阿帕奇火花 apache-spark-sql
下一篇:帶空間的突觸火花選擇列
