You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spark DataFrame新增月份列失败问题求助

问题描述

data set

我尝试在Spark的DataFrame中新增一列。我有一个清理后的数据集(dfClean),其中包含名为"Fecha ingreso"的日期列,想要从中提取月份并新增仅含月份的列。我尝试了以下代码:

from pyspark.sql.functions import month

dfCleanMonth = dfClean.withColumn('Month',month('Fecha ingreso'))
dfCleanMonth.display()

但未新增任何列,且无报错信息。请问该如何解决?

解决方案

首先,排查核心问题大概率是日期列的数据类型不对,或者列名引用的小问题,按以下步骤解决:

  • 检查日期列类型:执行dfClean.printSchema(),如果"Fecha ingreso"是string类型而非date/timestamp类型,month()函数无法解析有效日期,会返回null,看起来像是没新增列(实际已新增但值全为空)。

  • 转换日期类型后提取月份:如果是字符串格式的日期,先通过to_date()转换为标准日期类型(需匹配你的实际日期格式,比如dd/MM/yyyy,根据数据集调整):

from pyspark.sql.functions import to_date, month

# 替换日期格式为你的数据集实际格式
dfClean = dfClean.withColumn("Fecha ingreso", to_date("Fecha ingreso", "dd/MM/yyyy"))
dfCleanMonth = dfClean.withColumn('Month', month('Fecha ingreso'))
dfCleanMonth.display()
  • 兼容带空格的列名:列名包含空格时,用col()函数明确指定列可避免解析问题:
from pyspark.sql.functions import month, col

dfCleanMonth = dfClean.withColumn('Month', month(col('Fecha ingreso')))
# 直接查看目标列确认结果
dfCleanMonth.select("Fecha ingreso", "Month").display()
  • 强制查看指定列:如果DataFrame列数过多,display可能未展示新增列,可直接指定列查看:
dfCleanMonth.select("Fecha ingreso", "Month").show()

内容的提问来源于stack exchange,提问作者Vivian Roberts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:01:20