PySpark withColumn & withField TypeError: 'Column' object is not callable
PySpark withColumn & withField TypeError: 'Column' object is not callable
我似乎无法弄清楚如何使用 withField
更新嵌套数据框列,我似乎总是得到 'TypeError: 'Column' object is not callable'
.
我遵循了这个例子:
https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.Column.withField.html
df = spark.createDataFrame([Row(a=Row(b=1, c=2))])
df.withColumn('a', df['a'].withField('b', lit(3))).select('a.b').show()
结果仍然是:
Traceback (most recent call last):
File "C:\Users\benhalicki\Source\SparkTest\spark_nested_df_test.py", line 58, in <module>
df.withColumn('a', df['a'].withField('b', lit(3))).select('a.b').show()
TypeError: 'Column' object is not callable
Spark 版本:3.0.3(在 Windows 上)。
我做错了什么吗?
withField
是在 Spark 版本 3.1.0 中引入的,但您使用的是版本 3.0.3。如果您查看 documentation,您会看到有关版本支持的说明:
An expression that adds/replaces a field in StructType
by name.
New in version 3.1.0.
对于旧版本,您需要重新创建结构列 a
以更新字段:
from pyspark.sql import functions as F
df.withColumn(
'a',
F.struct(F.lit(3).alias("b"), F.col("a.c").alias("c"))
).select('a.b').show()
#+---+
#| b|
#+---+
#| 3|
#+---+
我似乎无法弄清楚如何使用 withField
更新嵌套数据框列,我似乎总是得到 'TypeError: 'Column' object is not callable'
.
我遵循了这个例子: https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.Column.withField.html
df = spark.createDataFrame([Row(a=Row(b=1, c=2))])
df.withColumn('a', df['a'].withField('b', lit(3))).select('a.b').show()
结果仍然是:
Traceback (most recent call last):
File "C:\Users\benhalicki\Source\SparkTest\spark_nested_df_test.py", line 58, in <module>
df.withColumn('a', df['a'].withField('b', lit(3))).select('a.b').show()
TypeError: 'Column' object is not callable
Spark 版本:3.0.3(在 Windows 上)。
我做错了什么吗?
withField
是在 Spark 版本 3.1.0 中引入的,但您使用的是版本 3.0.3。如果您查看 documentation,您会看到有关版本支持的说明:
An expression that adds/replaces a field in
StructType
by name.New in version 3.1.0.
对于旧版本,您需要重新创建结构列 a
以更新字段:
from pyspark.sql import functions as F
df.withColumn(
'a',
F.struct(F.lit(3).alias("b"), F.col("a.c").alias("c"))
).select('a.b').show()
#+---+
#| b|
#+---+
#| 3|
#+---+