python - Spark:基于模式填充空值的干净方法
问题描述
我有格式如下的 avro 文件:
|Some col|Some other col| body |
|--------|--------------|-----------------------|
|some val| some val | some json string |
| ... | ... | ... |
我用
spark.read.format("avro").load(file_path)
我想从那个 json 字符串中选择所有值,但是这个 json 被修剪了,所以只给出了值不是 None 的列。
我有一个模式,其中包含来自这些 json 文件的所有可能值(都可以为空)。
问题:是否有一种干净的方法可以从 json 字符串中选择所有列 + 模式中所有不在 json 字符串中的列,其中 None 作为插入值?
解决方案
In [1]: from pyspark.sql.types import StructField, StructType, StringType
...: from pyspark.sql.functions import col, from_json
In [2]: schema = StructType([
...: StructField("a", StringType()),
...: StructField("b", StringType()),
...: StructField("c", StringType()),
...: StructField("d", StringType()),
...: ])
In [3]: df = spark.createDataFrame([("1", '{"a": 1, "b": 2}'),
...: ("2", '{"a": 3, "c": 4}')],
...: schema=["Some col", "body"])
In [4]: df.show()
+--------+----------------+
|Some col| body|
+--------+----------------+
| 1|{"a": 1, "b": 2}|
| 2|{"a": 3, "c": 4}|
+--------+----------------+
In [5]: df.select(from_json(col("body"), schema).alias("data")).select("data.*").show()
+---+----+----+----+
| a| b| c| d|
+---+----+----+----+
| 1| 2|null|null|
| 3|null| 4|null|
+---+----+----+----+
推荐阅读
- reactjs - 做出反应。如何在组件树中调用特定子子项的方法
- php - 如何在 Codeigniter 4 中为所有页面设置特定语言
- opencv - 使用 opencv 查找直观的图像方向
- python - python dash应用程序中的蓝色圆圈是什么?
- firebase - 在 Firestore 文档中引用图像的正确方法
- java - 是否有一个非递归的解决方案来获取所有可能的字符串数组连接的列表?
- wordpress - 创建一个包含子页面的页面,并让每个子页面都有自己的页面模板
- asp.net-core - 不显眼的验证不适用于 ViewComponents
- python - 删除 Jupyter notebook pdf 中的命令大纲(颜色框或框架)
- r - 从序列创建组