将pyspark.sql.dataframe.DataFrame类型转换为Dictionary

时间:2016-12-18 07:15:02

标签: python dictionary apache-spark pyspark

我有一个pyspark Dataframe,我需要将其转换为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()

但它给出了错误。我怎样才能实现这个目标

4 个答案:

答案 0 :(得分:9)

您需要先使用pandas.DataFrame转换为toPandas(),然后您可以使用to_dict()转置数据框中的orient='list'方法:

df.toPandas().set_index('name').T.to_dict('list')
# Out[1]: {u'Alice': [10, 80]}

答案 1 :(得分:8)

请参阅以下示例:

>>> 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进行加载。然后我们通过在逗号上拆分将行转换为列。然后我们将原生RDD转换为DF并将名称添加到colume中。最后,我们将列转换为适当的格式。

然后我们收集驱动程序的所有内容,并使用一些python列表理解我们将数据转换为首选的表单。我们使用Row方法将asDict()对象转换为字典。在输出中我们可以看到Alice只出现一次,但这当然是因为Alice的密钥被覆盖了。

请记住,在将结果返回给驱动程序之前,您希望在pypspark中进行所有处理和过滤。

希望这会有所帮助,欢呼。

答案 2 :(得分:0)

RDD内置了asDict()函数,该函数允许将每一行表示为字典。

如果您有数据帧df,则需要将其转换为rdd并应用asDict()。

new_rdd = df.rdd.map(lambda row: row.asDict(True))

然后可以使用new_rdd执行常规的python映射操作,例如:

# You can define normal python functions like below and plug them when needed
def transform(row):
    # Add a new key to each row
    row["new_key"] = "my_new_value"
    return row

new_rdd = new_rdd.map(lambda row: transform(row))

答案 3 :(得分:-2)

如果行中嵌入了行,则可以执行此操作 df.asDict(recursive=True)