代码之家  ›  专栏  ›  技术社区  ›  Techno04335

如何将python数据帧转换为JSON

  •  0
  • Techno04335  · 技术社区  · 4 年前

    我在databricks环境中使用pyspark,我有一个如下的数据帧:

    display(TestDF)
    
    Count          Value
    10             Blue
    5              Green
    21             Red
    

    {"Blue":10,"Green":5,"Red":21}
    

    TestDF = TestDF.tojson()
    
    {"count":10,"value":"Blue"}
    {"count":5,"value":"Green"}
    {"count":21,"value":"Red"}
    

    谢谢。

    2 回复  |  直到 4 年前
        1
  •  4
  •   notNull    4 年前

    我们可以用 map_from_arrays Spark-2.4+ collect_list count,value

    #if count type is not int then cast to array<int>
    df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array<int>"))).alias("json")).\
    show(10,False)
    
    #if count type int then no need to casting
    df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array<int>"))).alias("json")).\
    show(10,False)
    #+------------------------------+
    #|json                          |
    #+------------------------------+
    #|{"Blue":10,"Green":5,"Red":21}|
    #+------------------------------+
    
    #get as string
    df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array<int>"))).alias("json")).collect()[0][0]
    #or
    df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array<int>"))).alias("json")).collect()[0]['json']
    #{"Blue":10,"Green":5,"Red":21}