python - 将 pyspark 数据框转换为 python 字典列表
问题描述
嗨,我是 pyspark 的新手,我正在尝试将 pyspark.sql.dataframe 转换为字典列表。
下面是我的数据框,类型是 <class 'pyspark.sql.dataframe.DataFrame'>:
+------------------+----------+------------------------+
| title|imdb_score|Worldwide_Gross(dollars)|
+------------------+----------+------------------------+
| The Eight Hundred| 7.2| 460699653|
| Bad Boys for Life| 6.6| 426505244|
| Tenet| 7.8| 334000000|
|Sonic the Hedgehog| 6.5| 308439401|
| Dolittle| 5.6| 245229088|
+------------------+----------+------------------------+
我想将其转换为:
[{"title":"The Eight Hundred", "imdb_score":7.2, "Worldwide_Gross(dollars)":460699653},
{"title":"Bad Boys for Life", "imdb_score":6.6, "Worldwide_Gross(dollars)":426505244},
{"title":"Tenet", "imdb_score":7.8, "Worldwide_Gross(dollars)":334000000},
{"title":"Sonic the Hedgehog", "imdb_score":6.5, "Worldwide_Gross(dollars)":308439401},
{"title":"Dolittle", "imdb_score":5.6, "Worldwide_Gross(dollars)":245229088}]
我该怎么做?提前致谢!
解决方案
您可以将每一行映射到字典中并收集结果:
df.rdd.map(lambda row: row.asDict()).collect()
推荐阅读
- git - git subtree split error: 您需要从工作树的顶层运行此命令
- java - 什么可以是 colspan 和 rowspan 属性的替换标记
- reactjs - PDFTron 在尝试使用反应加载 pdf 时给出错误
- swift - 斯威夫特:从另一个弹出窗口呈现一个弹出窗口
- python - 使用 pandas 有效地计算大型数据帧的每个时间箱的值
- java - Katalon Studio 未启动
- spring - Spring Cloud Gateway 中 API 的响应时间等指标
- php - WooCommerce:仅在单个产品页面上显示价格后缀 - 不适用于相关产品
- python - Flask 应用程序在本地主机中运行时抛出“未找到”错误
- ios - 使用 Accelerate 框架将单精度浮点值转换为 Int 16