无法将Spark数据框转换为Pandas数据框

时间:2020-04-12 06:05:28

标签: pandas dataframe apache-spark pyspark apache-spark-sql

我有一个Spark数据框Df,包含约13万行,5000个客户ID和7000个产品ID。我正在使用交叉连接生成所有可能的客户ID和产品ID组合(3400万行),并将其存储在fullouter中。我正在从Df中已经存在的fullouter中删除组合,然后使用我的模型找到allPredictions。

到目前为止一切顺利。但是我想将所有的预测(3000万行)转换为熊猫数据框。我知道通过toPandas()进行转换将很困难,因为没有行。因此,我所做的是,我仅对每个客户ID进行了前1位的预测-使用Windows函数和行号函数进行了此预测。

我假设allPredictions的大小应减少到5000个客户*每个客户1个预测= 5000行。我“假设”是因为count()花费的时间也太长,无法返回行数。 toPandas()应该在topPredictions数据框右边起作用。但这不起作用。花费了超过40分钟的时间,并且由于我在Google Colab工作,因此该会话在一段时间后变得无效。

我是Spark的新手。我在这里做错什么了吗?我应该对代码进行哪些更改?另外,我尝试将其写为实木复合地板-花费的时间太长。我也尝试过write.csv-同样的问题。

conf = SparkConf().setAppName("trial")
conf.set("spark.sql.execution.arrow.enabled",'true')
conf.set("spark.rpc.message.maxSize",'1024mb')
conf.set("spark.executor.memory", '8g')
conf.set('spark.executor.cores', '8')
conf.set('spark.cores.max', '8')
conf.set("spark.driver.memory", '45g')
conf.set('spark.driver.maxResultSize', '21G')
conf.set("spark.driver.bindAddress", '127.0.0.1')
conf.set("spark.worker.cleanup.enabled",True)
conf.set("spark.executor.heartbeatInterval", "200000")
conf.set("spark.network.timeout", "300000")
self.sparkContext = SparkContext().getOrCreate(conf=conf)
self.sparkContext.setCheckpointDir('/checkpoint')
best_als = ALS(rank=10, maxIter=20, regParam=1.0,alpha=200.0, userCol="customerId",itemCol="productId",ratingCol="purch",implicitPrefs=True)

model=best_als.fit(Df)

df1 = Df.select("customerId")
df2 = Df.select("productId")

fullouter = df1.crossJoin(df2)

bigtest=fullouter.join(data, ["customerId","productId"],"left_anti")

allPredictions=model.transform(bigtest)

from pyspark.sql.window import Window
from pyspark.sql.functions import rank, col, row_number

window = Window.partitionBy(allPredictions['customerId']).orderBy(allPredictions['prediction'].desc())

top_allPredictions=allPredictions.select('*', row_number().over(window).alias('rank')).filter(col('rank') <= 1)

dataframe=top_allPredictions.toPandas()

1 个答案:

答案 0 :(得分:0)

尝试

from pyspark.sql import *  
from pyspark.sql.functions import *  
from pyspark.sql.types import *  
import numpy as np    
import pandas as pd


dataframe= top_allPredictions.select("*").toPandas()