python - pyspark 'DataFrame' 对象没有属性 '_get_object_id'
问题描述
我正在尝试运行一些代码,但出现错误:
'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")))
解决方案
除非您使用连接,否则您不能在函数内引用第二个 spark DataFrame。IIUC,您可以执行以下操作以达到您想要的结果。
假设means
如下:
#means.show()
#+---+---------+
#| id|avg(col1)|
#+---+---------+
#| 1| 12.0|
#| 3| 300.0|
#| 2| 21.0|
#+---+---------+
加入df
并means
在id
列上,然后应用您的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|
#+---+-----+
但在这种情况下,我实际上建议使用Window
with pyspark.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|
#+---+-----+
推荐阅读
- visual-studio-code - 在 WSL 中运行 vscode 会引发 v8 二进制文件和快照之间的致命错误版本不匹配
- graphql - Keystone.JS API 用户认证(不是 Admin-UI)
- android - 如何将 Workmanager 任务完成通知服务?
- sql - 将表达式转换为数据类型日期时间的算术溢出错误
- selenium - 如何在 Cucumber+Selenium+Java 中实现 ITestListener
- amazon-web-services - 禁用 Cloudfront 以缓存特定路径
- firebase - 检测身份验证凭据是否已在 Firebase 中链接
- css - 卡内的 TableCell 文本在 React 中溢出
- azure-active-directory - 在 Azure AD B2C 中使用自定义策略设置电话注册和登录
- javascript - 使用 NPM 导入 D3?