【发布时间】:2023-01-19 22:43:45
【问题描述】:
你能帮我理解以下错误信息及其背后的原因吗:
创建一个虚拟数据集:
df_=spark.createDataFrame([(1, np.nan,'x'), (None, 2.0,'y'),(3,4.0,None)], ("a", "b","c"))
df_.show()
+----+---+----+
| a| b| c|
+----+---+----+
| 1|NaN| x|
|null|2.0| y|
| 3|4.0|null|
+----+---+----+
现在,我尝试通过以下方式替换“b”列中的 NaN:
df_.withColumn("b", df_.select("b").replace({float("nan"):5}).b)
df_.select("b").replace({float("nan"):5}).b 运行得很好,并给出了一个具有预期值的正确列。但是上面的代码不起作用,我无法理解错误
我得到的错误是:
AnalysisException Traceback (most recent call last)
Cell In[170], line 1
----> 1 df_.withColumn("b", df_.select("b").replace({float("nan"):5}).b)
File /usr/lib/spark/python/pyspark/sql/dataframe.py:2455, in DataFrame.withColumn(self, colName, col)
2425 """
2426 Returns a new :class:`DataFrame` by adding a column or replacing the
2427 existing column that has the same name.
(...)
2452
2453 """
2454 assert isinstance(col, Column), "col should be Column"
-> 2455 return DataFrame(self._jdf.withColumn(colName, col._jc), self.sql_ctx)
File /opt/conda/miniconda3/lib/python3.8/site-packages/py4j/java_gateway.py:1304, in JavaMember.__call__(self, *args)
1298 command = proto.CALL_COMMAND_NAME +\
1299 self.command_header +\
1300 args_command +\
1301 proto.END_COMMAND_PART
1303 answer = self.gateway_client.send_command(command)
-> 1304 return_value = get_return_value(
1305 answer, self.gateway_client, self.target_id, self.name)
1307 for temp_arg in temp_args:
1308 temp_arg._detach()
File /usr/lib/spark/python/pyspark/sql/utils.py:117, in capture_sql_exception.<locals>.deco(*a, **kw)
113 converted = convert_exception(e.java_exception)
114 if not isinstance(converted, UnknownException):
115 # Hide where the exception came from that shows a non-Pythonic
116 # JVM exception message.
--> 117 raise converted from None
118 else:
119 raise
AnalysisException: Resolved attribute(s) b#1083 missing from a#930L,b#931,c#932 in operator !Project [a#930L, b#1083 AS b#1085, c#932]. Attribute(s) with the same name appear in the operation: b. Please check if the right attribute(s) are used.;
!Project [a#930L, b#1083 AS b#1085, c#932]
+- LogicalRDD [a#930L, b#931, c#932], false
我可以通过在替换 API 中使用子集参数来实现所需的目标。即df_.replace({float("nan"):5},subset = ['b']) 但是,我试图更好地理解我看到的错误及其背后的原因。
【问题讨论】:
-
谢谢你的回答。但是,我的窘境与填写缺失值无关。我能做到。通过这个例子,我试图理解火花中的一些细微差别,这些细微差别不允许我使用我提到的方法,希望我能学到一些关于 withColumn 的东西。在 withColumn 中,我提供了数据框中现有列的转换。我不明白出了什么问题,为什么我会看到上面提到的错误
标签: apache-spark pyspark apache-spark-sql