【发布时间】:2019-06-08 09:13:23
【问题描述】:
让我把这个问题分解成一个更小的部分。我在 PySpark 中有一个 DataFrame,其中有一个 arrival_date 的列 date 格式 -
from pyspark.sql.functions import to_date
values = [('22.05.2016',),('13.07.2010',),('15.09.2012',),(None,)]
df = sqlContext.createDataFrame(values,['arrival_date'])
#Following code line converts String into Date format
df = df.withColumn('arrival_date',to_date(col('arrival_date'),'dd.MM.yyyy'))
df.show()
+------------+
|arrival_date|
+------------+
| 2016-05-22|
| 2010-07-13|
| 2012-09-15|
| null|
+------------+
df.printSchema()
root
|-- arrival_date: date (nullable = true)
在对DataFrame进行了很多转换之后,我终于想把缺失的日期填上,标记为null和01-01-1900。
一种方法 将列arrival_date 转换为String,然后以这种方式替换缺失值-df.fillna('1900-01-01',subset=['arrival_date']),最后重新转换此列to_date。这很不雅。
以下代码行无法正常工作,我得到一个错误-
df = df.fillna(to_date(lit('1900-01-01'),'yyyy-MM-dd'), subset=['arrival_date'])
文档说 The value must be of the following type: Int, Long, Float, Double, String, Boolean.
另一种方法是使用withColumn()和when() -
df = df.withColumn('arrival_date',when(col('arrival_date').isNull(),to_date(lit('01.01.1900'),'dd.MM.yyyy')).otherwise(col('arrival_date')))
有没有一种方法,我可以使用某些函数将我选择的日期直接分配给date 格式的列?
谁有更好的建议?
【问题讨论】:
-
你有没有想过这个问题?
-
上次使用 PySpark 之前,我找不到一个简单的解决方案。可能在最近 2 年他们在新版本中有一些东西,不知道。
标签: python date apache-spark fillna