我有一个 pyspark 数据框,我需要将其转换为 python 字典。
下面的代码是可重现的:
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()
有了这个数据框后,我需要将它转换成字典。
我试过这样
df.set_index('name').to_dict()
但是它给出了错误。我怎样才能做到这一点
最佳答案
请看下面的例子:
>>> from pyspark.sql.functions import col
>>> df = (sc.textFile('data.txt')
.map(lambda line: line.split(","))
.toDF(['name','age','height'])
.select(col('name'), col('age').cast('int'), col('height').cast('int')))
+-----+---+------+
| name|age|height|
+-----+---+------+
|Alice| 5| 80|
| Bob| 5| 80|
|Alice| 10| 80|
+-----+---+------+
>>> list_persons = map(lambda row: row.asDict(), df.collect())
>>> list_persons
[
{'age': 5, 'name': u'Alice', 'height': 80},
{'age': 5, 'name': u'Bob', 'height': 80},
{'age': 10, 'name': u'Alice', 'height': 80}
]
>>> dict_persons = {person['name']: person for person in list_persons}
>>> dict_persons
{u'Bob': {'age': 5, 'name': u'Bob', 'height': 80}, u'Alice': {'age': 10, 'name': u'Alice', 'height': 80}}
我用来测试 data.txt
的输入:
Alice,5,80
Bob,5,80
Alice,10,80
首先,我们通过读取行来使用 pyspark 进行加载。然后我们通过在逗号上拆分将行转换为列。然后我们将 native RDD 转换为 DF 并将名称添加到列中。最后我们将列转换为适当的格式。
然后我们将所有内容收集到驱动程序,并使用一些 python 列表理解将数据转换为首选形式。我们使用 asDict()
方法将 Row
对象转换为字典。在输出中我们可以观察到 Alice 只出现了一次,但这当然是因为 Alice 的 key 被覆盖了。
请记住,在将结果返回给驱动程序之前,您希望在 pypspark 中进行所有处理和过滤。
希望这有帮助,干杯。
关于python - 将 pyspark.sql.dataframe.DataFrame 类型 Dataframe 转换为 Dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206255/