首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Dataframe创建Json

从Dataframe创建Json
EN

Stack Overflow用户
提问于 2020-06-15 11:27:49
回答 2查看 70关注 0票数 1

作为Spark的新手,我正在做一些事情,并面临着困难。任何线索都会有帮助。我正在尝试从我拥有的数据帧创建一个JSON,但是toJSON函数不能帮助我解决这个问题。因此,我的输出数据框如下所示:

代码语言:javascript
复制
+---------+------------------+-------------------------+
|booking_id|    status           |count(status)|
+---------+------------------+-------------------------+
|  132         |     rent count.       |                        6|
|  132         |     rent booked     |                      24|
|  132         |     rent delayed    |                        6|
|  134         |     rent booked     |                      34|
|  134         |     rent delayed.   |                       21|

我正在寻找的输出是一个dataframe,它将包含预订id和状态及其作为Json的计数。

代码语言:javascript
复制
+---------+-------------------------------------------+
|booking_id|    status_json         
+---------+-------------------------------------------+
|  132         |   { "rent count": 6, "rent booked": 24, "rent delayed": 6}  
|  134        |     { "rent booked": 34, "rent delayed": 21}

提前谢谢。

EN

回答 2

Stack Overflow用户

发布于 2020-06-15 11:55:19

对于Spark2.4,,请使用map_from_arrays.

代码语言:javascript
复制
from pyspark.sql import functions as F

df.groupBy("booking_id").agg(F.to_json(F.map_from_arrays(F.collect_list("status"),F.collect_list("count(status)")))\
                              .alias("status_json"))\
                              .show(truncate=False)


#+----------+--------------------------------------------------+
#|booking_id|status_json                                       |
#+----------+--------------------------------------------------+
#|132       |{"rent count":6,"rent booked":24,"rent delayed":6}|
#|134       |{"rent booked":34,"rent delayed":21}              |
#+----------+--------------------------------------------------+
票数 3
EN

Stack Overflow用户

发布于 2020-06-15 13:17:19

代码语言:javascript
复制
  val sourceDF = Seq(
    (132, "rent count", 6),
    (132, "rent booked", 24),
    (132, "rent delayed", 6),
    (134, "rent booked", 34),
    (134, "rent delayed", 21)
  ).toDF("booking_id", "status", "count(status)")

  val resDF = sourceDF
    .groupBy("booking_id")
    .agg(to_json(collect_list(map(col("status"), col("count(status)")))).alias("status_json"))

  //  +----------+--------------------------------------------------------+
  //  |booking_id|status_json                                             |
  //  +----------+--------------------------------------------------------+
  //  |132       |[{"rent count":6},{"rent booked":24},{"rent delayed":6}]|
  //  |134       |[{"rent booked":34},{"rent delayed":21}]                |
  //  +----------+--------------------------------------------------------+
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62380879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档