将pyspark.sql.dataframe.DataFrame类型Dataframe转换为Dictionary [英] Convert pyspark.sql.dataframe.DataFrame type Dataframe to Dictionary
本文介绍了将pyspark.sql.dataframe.DataFrame类型Dataframe转换为Dictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个pyspark数据框,我需要将其转换为python字典.
I have a pyspark Dataframe and I need to convert this into python dictionary.
下面的代码是可重现的:
Below code is reproducible:
from pyspark.sql import Row
rdd = sc.parallelize([Row(name='Alice', age=5, height=80),Row(name='Alice', age=5, height=80),Row(name='Alice', age=10, height=80)])
df = rdd.toDF()
一旦有了此数据框,就需要将其转换为字典.
Once I have this dataframe, I need to convert it into dictionary.
我尝试过这样
df.set_index('name').to_dict()
但是它给出了错误.我该如何实现
But it gives error. How can I achieve this
推荐答案
您需要先使用toPandas()
转换为pandas.DataFrame
,然后才能在具有orient='list'
的转置数据帧上使用to_dict()
方法:
You need to first convert to a pandas.DataFrame
using toPandas()
, then you can use the to_dict()
method on the transposed dataframe with orient='list'
:
df.toPandas().set_index('name').T.to_dict('list')
# Out[1]: {u'Alice': [10, 80]}
这篇关于将pyspark.sql.dataframe.DataFrame类型Dataframe转换为Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文