如何从字典创建数据框,其中每个项目都是 PySpark 中的一列

How to create an dataframe from a dictionary where each item is a column in PySpark

我想从字典中创建一个新的数据框。该字典包含作为键的列名称和作为值的列数据列表。例如:

col_dict = {'col1': [1, 2, 3],
            'col2': [4, 5, 6]}

我需要这样的数据框:

+------+------+
| col1 | col2 |
+------+------+
|     1|     4|
|     2|     5|
|     3|     6|
+------+------+

似乎没有简单的方法可以做到这一点。

最简单的方法是创建一个 pandas DataFrame 并转换为 Spark DataFrame:

与Pandas

col_dict = {'col1': [1, 2, 3],
            'col2': [4, 5, 6]}

import pandas as pd
pandas_df = pd.DataFrame(col_dict)
df = sqlCtx.createDataFrame(pandas_df)
df.show()
#+----+----+
#|col1|col2|
#+----+----+
#|   1|   4|
#|   2|   5|
#|   3|   6|
#+----+----+

没有Pandas

如果 pandas 不可用,您只需将数据处理成适用于 createDataFrame() 函数的形式。引用我自己的话 :

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.

colnames, data = zip(*col_dict.items())
print(colnames)
#('col2', 'col1')
print(data)
#([4, 5, 6], [1, 2, 3])

现在我们需要修改数据,使其成为一个元组列表,其中每个元素都包含对应列的数据。幸运的是,使用 zip:

很容易
data = zip(*data)
print(data)
#[(4, 1), (5, 2), (6, 3)]

现在打电话给createDataFrame():

df = sqlCtx.createDataFrame(data, colnames)
df.show()
#+----+----+
#|col2|col1|
#+----+----+
#|   4|   1|
#|   5|   2|
#|   6|   3|
#+----+----+