我正在尝试转换以下 Python dict
进入 PySpark DataFrame 但我没有得到预期的输出。
dict_lst = {'letters': ['a', 'b', 'c'],
'numbers': [10, 20, 30]}
df_dict = sc.parallelize([dict_lst]).toDF() # Result not as expected
df_dict.show()
有没有办法在不使用 Pandas 的情况下做到这一点?
最佳答案
报价myself :
I find it's useful to think of the argument to createDataFrame() as a list of tuples where each entry in the list corresponds to a row in the DataFrame and each element of the tuple corresponds to a column.
所以最简单的就是把你的字典转换成这种格式。您可以使用
zip()
轻松完成此操作:column_names, data = zip(*dict_lst.items())
spark.createDataFrame(zip(*data), column_names).show()
#+-------+-------+
#|letters|numbers|
#+-------+-------+
#| a| 10|
#| b| 20|
#| c| 30|
#+-------+-------+
以上假设所有列表的长度相同。如果不是这种情况,您将不得不使用
itertools.izip_longest
(python2) 或 itertools.zip_longest
( python 3)。from itertools import izip_longest as zip_longest # use this for python2
#from itertools import zip_longest # use this for python3
dict_lst = {'letters': ['a', 'b', 'c'],
'numbers': [10, 20, 30, 40]}
column_names, data = zip(*dict_lst.items())
spark.createDataFrame(zip_longest(*data), column_names).show()
#+-------+-------+
#|letters|numbers|
#+-------+-------+
#| a| 10|
#| b| 20|
#| c| 30|
#| null| 40|
#+-------+-------+
关于来自没有 Pandas 的 Python 字典的 PySpark 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51554921/