gpt4 book ai didi

apache-spark - PySpark withColumn & withField 类型错误 : 'Column' object is not callable

转载 作者:行者123 更新时间:2023-12-05 05:50:11 25 4
gpt4 key购买 nike

我似乎无法弄清楚如何使用 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|
#+---+

关于apache-spark - PySpark withColumn & withField 类型错误 : 'Column' object is not callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70547883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com