【发布时间】:2020-02-13 20:53:15
【问题描述】:
我有 pyspark dataframe 一些数据,我想 substring 列的一些数据,该列还包含一些 null 值。
这是我的数据框
+-------------+
| Name|
+--------------+
| Asia201909284|
| US20190928|
|Europ201909287|
| null|
| something|
| nothing|
+--------------+
我想从Name 列中删除Asia, US, Europ
这是我已经尝试过的代码。
fun_asia = udf(lambda x: x[4:len(x)])
fun_us = udf(lambda x: x[2:len(x)])
fun_europ = udf(lambda x: x[5:len(x)])
df1.withColumn("replace", \
when(df1.Name.isNull(),df1.Name)\
.when(df1.Name.like("Asia%"),fun_asia(col('Name')))\
.when(df1.Name.like("US%"),fun_us(col('Name')))\
.when(df1.Name.like("Europ%"),fun_europ(col('Name')))
.otherwise(df1.Name)
).show()
如果该列中没有 null 值,它可以正常工作。但如果有一些 null 值,它会给出类似 len() 无法计算空值的错误。
错误消息
TypeError: object of type 'NoneType' has no len()
我很困惑为什么它的调用乐趣也为null 值。
以及如何克服我的问题并获得我想要的结果,任何帮助表示感谢。
我想要的实际结果
+--------------+---------+
| Name| replace|
+--------------+---------+
| Asia201909284|201909284|
| US20190928| 20190928|
|Europ201909287|201909287|
| null| null|
| something|something|
| nothing| nothing|
+--------------+---------+
【问题讨论】:
-
为什么不删除空值?
-
它的演示数据框这就是为什么我只显示一列,但在我的真实数据框中有不止一列,所以我需要那个也有空值的记录。
-
我想我在下面提供了正确的解决方案。请尝试一下。如果有帮助,请点赞并选择。尝试第二种解决方案,我认为对您来说更好。
标签: python-3.x dataframe pyspark azure-databricks