scala - 从具有键值对的列中获取部分值并将其分配给 Spark Dataframe 中的新列
问题描述
我有一个如下的数据框
+----+-----------------------------+
|id | att |
+----+-----------------------------+
| 25 | {"State":"abc","City":"xyz"}|
| 26 | null |
| 27 | {"State":"pqr"} |
+----+-----------------------------+
如果 att 列具有 city 属性,我想要一个具有列 id 和 city 的数据框,否则为 null
+----+------+
|id | City |
+----+------+
| 25 | xyz |
| 26 | null |
| 27 | null |
+----+------+
语言:斯卡拉
解决方案
您可以使用from_json解析您的 json 数据并将其转换为 Map。然后使用以下方法之一访问地图项:
- Column 类的getItem方法
- 默认访问器,即
map("map_key")
- element_at函数
import org.apache.spark.sql.functions.from_json
import org.apache.spark.sql.types.{MapType, StringType}
import sparkSession.implicits._
val df = Seq(
(25, """{"State":"abc","City":"xyz"}"""),
(26, null),
(27, """{"State":"pqr"}""")
).toDF("id", "att")
val schema = MapType(StringType, StringType)
df.select($"id", from_json($"att", schema).getItem("City").as("City"))
//or df.select($"id", from_json($"att", schema)("City").as("City"))
//or df.select($"id", element_at(from_json($"att", schema), "City").as("City"))
// +---+----+
// | id|City|
// +---+----+
// | 25| xyz|
// | 26|null|
// | 27|null|
// +---+----+
推荐阅读
- python - 在 Visual Studio 代码中同时运行两个 python 文件
- cassandra - 使用二级索引超时的 Cassandra 查询
- python - 调整单个子图间距
- java - Spring Data JPA“ON DUPLICATE KEY UPDATE amount = account.amount + someValue”
- javascript - 年历 - alwaysHalfDay 不工作
- excel - 验证包含数字和文本excel的单元格
- c++ - std 容器在 dll 上泄漏内存
- azure - Azure 应用服务预生产槽应使用哪些设置?
- python - Instagram api没有解码
- powerbi - Power BI 中的动态选择值