如何在另一個數據幀上執行UDF時引用pyspark數據框?Pyspark:如何在另一個數據框中的UDF中引用數據框?
這是一個虛擬的例子。我創建了兩個數據幀scores
和lastnames
,並且在每個數據幀中存在兩個數據幀相同的列。在應用於scores
的UDF中,我想過濾lastnames
並返回在lastname
中找到的字符串。
from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.sql import SQLContext
from pyspark.sql.types import *
sc = SparkContext("local")
sqlCtx = SQLContext(sc)
# Generate Random Data
import itertools
import random
student_ids = ['student1', 'student2', 'student3']
subjects = ['Math', 'Biology', 'Chemistry', 'Physics']
random.seed(1)
data = []
for (student_id, subject) in itertools.product(student_ids, subjects):
data.append((student_id, subject, random.randint(0, 100)))
from pyspark.sql.types import StructType, StructField, IntegerType, StringType
schema = StructType([
StructField("student_id", StringType(), nullable=False),
StructField("subject", StringType(), nullable=False),
StructField("score", IntegerType(), nullable=False)
])
# Create DataFrame
rdd = sc.parallelize(data)
scores = sqlCtx.createDataFrame(rdd, schema)
# create another dataframe
last_name = ["Granger", "Weasley", "Potter"]
data2 = []
for i in range(len(student_ids)):
data2.append((student_ids[i], last_name[i]))
schema = StructType([
StructField("student_id", StringType(), nullable=False),
StructField("last_name", StringType(), nullable=False)
])
rdd = sc.parallelize(data2)
lastnames = sqlCtx.createDataFrame(rdd, schema)
scores.show()
lastnames.show()
from pyspark.sql.functions import udf
def getLastName(sid):
tmp_df = lastnames.filter(lastnames.student_id == sid)
return tmp_df.last_name
getLastName_udf = udf(getLastName, StringType())
scores.withColumn("last_name", getLastName_udf("student_id")).show(10)
而下面是跟蹤的最後一部分:
Py4JError: An error occurred while calling o114.__getnewargs__. Trace:
py4j.Py4JException: Method __getnewargs__([]) does not exist
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:335)
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:344)
at py4j.Gateway.invoke(Gateway.java:252)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:209)
at java.lang.Thread.run(Thread.java:745)
您不能在UDF內部訪問'df',因爲它將在執行程序中處理,'df' ref只能從驅動程序訪問。你可以使用廣播變量作爲'lastnames'。讓我知道是否需要任何幫助。 – mrsrinivas
但是考慮將'lastnames'加入'scores'而不是從UDF中加入。 – mrsrinivas
嗨@mrsrinivas,謝謝你的回覆。首先我不能加入,因爲即使這個虛擬示例可以使用連接來解決,在我的實際實現中,我需要在UDF中執行更多的處理。其次,是的!我如何在這種情況下使用廣播變量? – tohweizhong