我似乎無法弄清楚如何使用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 上)。
我在做一些根本錯誤的事情嗎?
uj5u.com熱心網友回復:
withField是在 Spark 版本3.1.0 中引入的,但您使用的是版本 3.0.3。如果您查看檔案,您可以看到有關版本支持的提及:
StructType按名稱添加/替換欄位的運算式。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|
# ---
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/401927.html
上一篇:在GoogleColab上創建sparkContext會給出:`RuntimeError:Javagatewayprocessexitedbeforesentitsportnumber`
