python - 如何将python数据帧转换为JSON
问题描述
我在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"}
谢谢。
解决方案
我们可以使用map_from_arrays
fromSpark-2.4+
和collect_list
oncount,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}
推荐阅读
- rest - Keycloak 服务到服务
- flutter - TypeError(类型“用户”不是“FutureOr”类型的子类型
>'),即使返回值类型相同 - django - `django-cron==0.5.0` 无法在 `python:2.7` 和 `python:2.7-slim-buster` docker 映像中运行计划的 cron 作业
- azure-active-directory - Azure AD 中用于 Angular 应用程序的用户模拟
- intellij-idea - Docker compose 在 Intellij 的 zsh shell 中不起作用
- javascript - 当我的控制器抛出错误时,Jest 显示未定义
- javascript - IE11 setTimeout 需要更多时间来执行
- java - 尝试在 Ubuntu 上运行 Selenium 测试时出现问题
- ios - 如何以编程方式获取 Firebase InAppMessaging 实例 ID
- excel - 从 Google 表格复制特定范围并将值粘贴到 Excel