Skip to main content
 首页 » 编程设计

python之如何在 Python 中联合 Spark SQL 数据帧

2025年02月15日30oomusou

这里有几种创建数据帧联合的方法,当我们谈论大数据帧时,哪种方法(如果有的话)是最好的/推荐的?我应该先创建一个空数据框还是连续合并到创建的第一个数据框?

空数据框创建

from pyspark.sql.types import StructType, StructField, IntegerType, StringType 
 
schema = StructType([ 
    StructField("A", StringType(), False),  
    StructField("B", StringType(), False),  
    StructField("C", StringType(), False) 
]) 
 
pred_union_df = spark_context.parallelize([]).toDF(schema) 

方法 1 - 边走边合并:

for ind in indications: 
    fitted_model = get_fitted_model(pipeline, train_balanced_df, ind) 
    pred = get_predictions(fitted_model, pred_output_df, ind) 
    pred_union_df  = pred_union_df.union(pred[['A', 'B', 'C']]) 

方法 2 - 最后并集:

all_pred = [] 
for ind in indications: 
    fitted_model = get_fitted_model(pipeline, train_balanced_df, ind) 
    pred = get_predictions(fitted_model, pred_output_df, ind) 
    all_pred.append(pred) 
pred_union_df = pred_union_df.union(all_pred) 

还是我全错了?

编辑: 方法 2 是不可能的,因为我认为它会来自这个 answer .我必须遍历列表并合并每个数据框。

请您参考如下方法:

方法 2 始终是首选,因为它避免了长沿袭问题。

虽然 DataFrame.union 只接受一个 DataFrame 作为参数,但是 RDD.union 做 take a list .鉴于您的示例代码,您可以在调用 toDF 之前尝试合并它们。

如果您的数据在磁盘上,您也可以尝试 load them all at once实现联合,例如,

dataframe = spark.read.csv([path1, path2, path3])