【问题标题】:How to convert python dataframe to JSON如何将python数据帧转换为JSON
【发布时间】:2020-09-06 06:34:23
【问题描述】:

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

display(TestDF)

Count          Value
10             Blue
5              Green
21             Red

如何将 DF 转换为 JSON 格式,如下所示:

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

我在下面尝试过,但是 JSON 的格式并不像上面那样正确

TestDF = TestDF.tojson()

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

谢谢。

【问题讨论】:

  • 如上通过 {"Blue" :10,......}
  • tojson有控制参数吗?您可能必须以某种方式转换数据框。看起来tojson 为每个row 创建了一个字典,并为每一列创建了一个键。

标签: python json dataframe apache-spark pyspark


【解决方案1】:

我们可以在 count,value 列中使用 Spark-2.4+collect_list 中的 map_from_arrays .

#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}

【讨论】:

  • 当我使用这个方法并打印时,我得到如下:` +---------+ |json | +-------------+ |{"蓝色":10,"绿色":5,"红色":21} | +-------------+ ` 我如何获取字符串:{"Blue":10,"Green":5,"Red":21} 有什么建议吗?谢谢
  • @Techno04335,试试df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array&lt;int&gt;"))).alias("json")).collect()[0][0]
  • 感谢您的帮助!
猜你喜欢
  • 2017-05-14
  • 2023-03-04
  • 2019-09-26
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 2023-03-16
  • 2023-03-31
  • 2019-08-31
相关资源
最近更新 更多