【发布时间】:2020-12-28 04:37:21
【问题描述】:
我正在尝试从嵌套的 pyspark DataFrame 生成 json 字符串,但正在丢失键值。 我的初始数据集类似于以下内容:
data = [
{"foo": [1, 2], "bar": [4, 5], "buzz": [7, 8]},
{"foo": [1], "bar": [4], "buzz": [7]},
{"foo": [1, 2, 3], "bar": [4, 5, 6], "buzz": [7, 8, 9]},
]
df = spark.read.json(sc.parallelize(data))
df.show()
## +---------+---------+---------+
## | bar| buzz| foo|
## +---------+---------+---------+
## | [4, 5]| [7, 8]| [1, 2]|
## | [4]| [7]| [1]|
## |[4, 5, 6]|[7, 8, 9]|[1, 2, 3]|
## +---------+---------+---------+
然后我使用 arrays_zip 将每一列压缩在一起:
df_zipped = (
df
.withColumn(
"zipped",
F.arrays_zip(
F.col("foo"),
F.col("bar"),
F.col("buzz"),
)
)
)
df_zipped.printSchema()
root
|-- bar: array (nullable = true)
| |-- element: long (containsNull = true)
|-- buzz: array (nullable = true)
| |-- element: long (containsNull = true)
|-- foo: array (nullable = true)
| |-- element: long (containsNull = true)
|-- zipped: array (nullable = true)
| |-- element: struct (containsNull = false)
| | |-- foo: long (nullable = true)
| | |-- bar: long (nullable = true)
| | |-- buzz: long (nullable = true)
问题是在压缩数组上使用 to_json。它会丢失 foo、bar 和 Buzz 键值,而是将键保存为元素索引
(
df_zipped
.withColumn("zipped", F.to_json("zipped"))
.select("zipped")
.show(truncate=False)
)
+-------------------------------------------------------------+
|zipped |
+-------------------------------------------------------------+
|[{"0":1,"1":4,"2":7},{"0":2,"1":5,"2":8}] |
|[{"0":1,"1":4,"2":7}] |
|[{"0":1,"1":4,"2":7},{"0":2,"1":5,"2":8},{"0":3,"1":6,"2":9}]|
+-------------------------------------------------------------+
如何保留“bar”、“buzz”和“foo”而不是 0、1、2?
【问题讨论】:
-
不漂亮,但您可以使用
transform手动构建字符串:类似于F.expr("""transform(zipped, x -> concat('{"foo":', x['foo'], '"bar":', x['bar'], '"buzz":', x['buzz'], '}'))""")
标签: python dataframe apache-spark pyspark apache-spark-sql