gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:01:44 24 4
gpt4 key购买 nike

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

空数据框创建

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.uniontake a list .鉴于您的示例代码,您可以在调用 toDF 之前尝试合并它们。

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

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

关于python - 如何在 Python 中联合 Spark SQL 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45551524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com