首页 > 解决方案 > PySpark:如何通过多处理并行处理数据帧的多列?

问题描述

我想QuantileDiscretizer在 pyspark 中添加数据框的列。但是有一些4,000列要转换。所以我想使用multiprocessing如下方法。

import multiprocessing as mp
import multiprocessing.pool
from pyspark.ml.feature import QuantileDiscretizer

def transform_col(train,col,numBuckets=5):
    '''
    return: df
    '''
    discretizer = QuantileDiscretizer(numBuckets=numBuckets, inputCol=col, outputCol=col + "_bin")
    discretizer = discretizer.fit(train)
    train = discretizer.transform(train)
    return train
# just an example.
train_df = spark.createDataFrame([[1,2],[3,4],[3,5],[8,8],[3,9],[8,1],[7,1]],["a","b"])
pool = mp.Pool(processes=mp.cpu_count() - 1)
# arguments
process_col = ["a","b"]
args = zip([train_df.select(col) for col in process_col],
           [col for col in process_col]
           )
res = dict(zip([col for col in process_col], pool.starmap(transform_col, args)))
for col in res.keys():
    train_df = train_df.withColumn("process_{}".format(col), res[col].select(col)).drop(col)
pool.close()
pool.join()

但我遇到以下错误。错误:

Py4JError: An error occurred while calling o385.__getstate__. Trace:
py4j.Py4JException: Method __getstate__([]) does not exist
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)
    at py4j.Gateway.invoke(Gateway.java:274)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)

那么,有没有什么方法可以解决这个问题呢?

标签: pythonapache-sparkpysparkmultiprocessing

解决方案


推荐阅读