pyspark的“DataFrame”对象没有属性“_get_object_id”。

10
我正在尝试运行一些代码,但是出现了错误:

'DataFrame'对象没有'_get_object_id'属性

代码如下:
items = [(1,12),(1,float('Nan')),(1,14),(1,10),(2,22),(2,20),(2,float('Nan')),(3,300),
         (3,float('Nan'))]

sc = spark.sparkContext
rdd = sc.parallelize(items)
df = rdd.toDF(["id", "col1"])

import pyspark.sql.functions as func
means = df.groupby("id").agg(func.mean("col1"))

# The error is thrown at this line
df = df.withColumn("col1", func.when((df["col1"].isNull()), means.where(func.col("id")==df["id"])).otherwise(func.col("col1"))) 

2
你不能在函数内部像这样使用第二个数据框 - 而应该使用连接(join)。 - pault
2个回答

10

除非使用连接,否则无法在函数内引用第二个spark DataFrame。如果我理解正确,您可以执行以下操作以实现所需的结果。

假设means如下:

#means.show()
#+---+---------+
#| id|avg(col1)|
#+---+---------+
#|  1|     12.0|
#|  3|    300.0|
#|  2|     21.0|
#+---+---------+

id列上将dfmeans连接,然后应用您的when条件。

from pyspark.sql.functions import when

df.join(means, on="id")\
    .withColumn(
        "col1",
        when(
            (df["col1"].isNull()), 
            means["avg(col1)"]
        ).otherwise(df["col1"])
    )\
    .select(*df.columns)\
    .show()
#+---+-----+
#| id| col1|
#+---+-----+
#|  1| 12.0|
#|  1| 12.0|
#|  1| 14.0|
#|  1| 10.0|
#|  3|300.0|
#|  3|300.0|
#|  2| 21.0|
#|  2| 22.0|
#|  2| 20.0|
#+---+-----+

但在这种情况下,我实际上建议使用Windowpyspark.sql.functions.mean

from pyspark.sql import Window
from pyspark.sql.functions import col, mean

df.withColumn(
    "col1",
    when(
        col("col1").isNull(), 
        mean("col1").over(Window.partitionBy("id"))
    ).otherwise(col("col1"))
).show()
#+---+-----+
#| id| col1|
#+---+-----+
#|  1| 12.0|
#|  1| 10.0|
#|  1| 12.0|
#|  1| 14.0|
#|  3|300.0|
#|  3|300.0|
#|  2| 22.0|
#|  2| 20.0|
#|  2| 21.0|
#+---+-----+

-5

我认为你正在使用Scala API,在其中使用()。 在PySpark中,请改用[]。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接