【发布时间】:2018-12-03 04:54:12
【问题描述】:
我想在 PySpark 数据框中拆分一列,该列(字符串类型)如下所示:
[{"quantity":25,"type":"coins","balance":35}]
[{"balance":40,"type":"coins","quantity":25}]
[{"quantity":2,"type":"column_breaker","balance":2},{"quantity":2,"type":"row_breaker","balance":2},{"quantity":2,"type":"single_block_breaker","balance":2},{"quantity":1,"type":"rainbow","balance":1},{"quantity":135,"type":"coins","balance":140}]
所以他们中的一些人有一组"quantity, type, balance",而他们中的一些人有多个这样的条目。我尝试将其视为 JSON 变量并拆分:
schema = StructType(
[
StructField('balance', StringType(), True),
StructField('type', StringType(), True),
StructField('quantity', StringType(), True)
]
)
temp = merger.withColumn("data",
from_json("items",schema)).select("items", col('data.*'))
display(temp)
但它只能将观察结果拆分为一组。我想要这样的输出
balance|quantity|type
35 | 25 |coins
40 | 25 |coins
.......
这样,一组观测值拆分为一个观测值,而多组观测值拆分为垂直放置的多个观测值。
另外,拆分成多行后,如何识别每个观察值?说,我有另一个变量是 ID,我该如何分配 ID?
【问题讨论】:
-
你能分享一下你想要的结果吗?
标签: python json split pyspark apache-spark-sql