PySpark:Python字典中所有数据帧的联合

2024-04-18 04:37:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典my_dict_of_df,它由每次运行程序时的变量个数据帧组成。我想创建一个新的数据帧,它是所有这些数据帧的联合。在

我的数据帧看起来像-

my_dict_of_df["df_1"], my_dict_of_df["df_2"] and so on...

如何联合所有这些数据帧?在


Tags: andof数据程序df字典soon
1条回答
网友
1楼 · 发布于 2024-04-18 04:37:08

参考了给定的here的解决方案,感谢@pault。在

from functools import reduce
from pyspark.sql import DataFrame

def union_all(*dfs):
    return reduce(DataFrame.union, dfs)

df1 = sqlContext.createDataFrame([(1, "foo1"), (2, "bar1")], ("k", "v"))
df2 = sqlContext.createDataFrame([(3, "foo2"), (4, "bar2")], ("k", "v"))
df3 = sqlContext.createDataFrame([(5, "foo3"), (6, "bar3")], ("k", "v"))

my_dic = {}
my_dic["df1"] = df1
my_dic["df2"] = df2
my_dic["df3"] = df3

new_df = union_all(*my_dic.values())

print(type(new_df))   # <class 'pyspark.sql.dataframe.DataFrame'>
print(new_df.show())  

"""
+ -+  +
|  k|   v|
+ -+  +
|  1|foo1|
|  2|bar1|
|  3|foo2|
|  4|bar2|
|  5|foo3|
|  6|bar3|
+ -+  +
"""

编辑:使用DataFrame.union而不是{},因为后者已被弃用。在

相关问题 更多 >