TypeError:在withColumn()中使用多个列时,列不可编辑

2024-05-13 15:06:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从日期列中查找季度开始日期。当我使用selectExpr()编写它时,我得到了预期的结果

df.selectExpr("add_months(history_effective_month,-(month(history_effective_month)%3)+1) as history_effective_qtr","history_effective_month").show(5)

output-

history_effective_qtr   history_effective_month

       2017-07-01                2017-06-01
       2016-04-01                2016-05-01
       2015-10-01                2015-09-01
       2012-01-01                2012-01-01
       2012-01-01                2012-01-01

但是当我在.withColumn()中添加相同的逻辑时,我得到了TypeError:Column不可编辑

^{pr2}$

我使用的解决方法如下

df=selectExpr('*',"date_sub(history_effective_date," \
   "dayofmonth(history_effective_date)-1) as history_effective_month")

Tags: adddfoutputdateasshow逻辑history
1条回答
网友
1楼 · 发布于 2024-05-13 15:06:54

TL;DR只需使用^{}

^{bq}$
df.select(
   "history_effective_quarter", add_months('history_effective_month',
   -(month('history_effective_month')%3)+1))

您的代码无法工作,因为^{}

withColumn(colName, col)

Returns a new DataFrame by adding a column or replacing the existing column that has the same name.

用于添加单个列

相关问题 更多 >