【问题标题】:I am wondering how to transfer the dataframe to json format我想知道如何将数据帧转换为 json 格式
【发布时间】:2020-08-14 02:52:42
【问题描述】:

我想知道如何将数据帧转换为 json 格式。

name   ㅣ type     ㅣ count
'james'ㅣ 'message'ㅣ 4
'kane' ㅣ 'text'   ㅣ 3
'james'ㅣ 'text'   ㅣ 2 
'kane' ㅣ 'message'ㅣ 3 

--------------结果------ --------------

数据帧到 json 格式

data = [
          {name : 'james', 'message' : 4, 'text; : 2}, {'name' : 'kane', 'message' :3, 'text' : 3}
       ]

如何将dataframe转成json数据?

【问题讨论】:

    标签: json dataframe pyspark


    【解决方案1】:

    您可以使用to_jsoncollect_list 函数。

    import pyspark.sql.functions as f
    
    df1 = df.withColumn('json', f.struct('name', 'type', 'count')) \
      .groupBy().agg(f.collect_list('json').alias('data')) \
      .withColumn('data', f.to_json(f.struct(f.col('data')))) \
      .show(10, False)
    
    +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    |data                                                                                                                                                                                      |
    +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    |{"data":[{"name":"james","type":"message","count":4.0},{"name":"kane","type":"text","count":3.0},{"name":"james","type":"text","count":2.0},{"name":"kane","type":"message","count":3.0}]}|
    +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    

    【讨论】:

    • 我想要分组数据和缺少类型键的数据
    • 答案已更新并满足我认为的所有条件:)
    • 我更改了示例。我该如何解决它
    • 我认为这个问题的最初目的现在不同了,所以请将你的问题恢复到原来的状态并发布另一个问题更好地找到答案。
    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2019-08-28
    • 2019-04-13
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    相关资源
    最近更新 更多