带有 space 字符 '\xa0' 的 Spark 过滤器奇怪行为
Spark filter weird behaviour with space character '\xa0'
我有一个包含多列和多行的 Delta 数据框。
我做了以下事情:
Delta.limit(1).select("IdEpisode").show()
+---------+
|IdEpisode|
+---------+
| 287 860|
+---------+
但是,当我这样做时:
Delta.filter("IdEpisode == '287 860'").show()
它 returns 0 行这很奇怪,因为我们可以清楚地看到数据框中存在 Id
。
我认为它与中间的 ' '
有关,但我不明白为什么它会成为问题以及如何解决它。
重要编辑:
Doing Delta.limit(1).select("IdEpisode").collect()[0][0]
返回:'287\xa0860'
然后做:
Delta.filter("IdEpisode == '287\xa0860'").show()
返回了我一直在寻找的行。有什么解释吗?
这个角色叫做NO-BREAK SPACE。这不是常规 space,这就是它与您的过滤不匹配的原因。
您可以在应用过滤器之前使用 regexp_replace
函数删除它:
import pyspark.sql.functions as F
Delta = spark.createDataFrame([('287\xa0860',)], ['IdEpisode'])
# replace NBSP character with normal space in column
Delta = Delta.withColumn("IdEpisode", F.regexp_replace("IdEpisode", '[\u00A0]', ' '))
Delta.filter("IdEpisode = '287 860'").show()
#+---------+
#|IdEpisode|
#+---------+
#| 287 860|
#+---------+
您还可以通过使用正则表达式 \p{Z}
将所有类型的 space 替换为常规 space:
来清理您的专栏
\p{Z}
or \p{Separator}
: any kind of whitespace or invisible separator.
Delta = Delta.withColumn("IdEpisode", F.regexp_replace("IdEpisode", '\p{Z}', ' '))
我有一个包含多列和多行的 Delta 数据框。
我做了以下事情:
Delta.limit(1).select("IdEpisode").show()
+---------+
|IdEpisode|
+---------+
| 287 860|
+---------+
但是,当我这样做时:
Delta.filter("IdEpisode == '287 860'").show()
它 returns 0 行这很奇怪,因为我们可以清楚地看到数据框中存在 Id
。
我认为它与中间的 ' '
有关,但我不明白为什么它会成为问题以及如何解决它。
重要编辑:
Doing Delta.limit(1).select("IdEpisode").collect()[0][0]
返回:'287\xa0860'
然后做:
Delta.filter("IdEpisode == '287\xa0860'").show()
返回了我一直在寻找的行。有什么解释吗?
这个角色叫做NO-BREAK SPACE。这不是常规 space,这就是它与您的过滤不匹配的原因。
您可以在应用过滤器之前使用 regexp_replace
函数删除它:
import pyspark.sql.functions as F
Delta = spark.createDataFrame([('287\xa0860',)], ['IdEpisode'])
# replace NBSP character with normal space in column
Delta = Delta.withColumn("IdEpisode", F.regexp_replace("IdEpisode", '[\u00A0]', ' '))
Delta.filter("IdEpisode = '287 860'").show()
#+---------+
#|IdEpisode|
#+---------+
#| 287 860|
#+---------+
您还可以通过使用正则表达式 \p{Z}
将所有类型的 space 替换为常规 space:
\p{Z}
or\p{Separator}
: any kind of whitespace or invisible separator.
Delta = Delta.withColumn("IdEpisode", F.regexp_replace("IdEpisode", '\p{Z}', ' '))