从Spark中的数据框列值中删除空格

时间:2016-02-21 19:35:40

标签: python apache-spark dataframe apache-spark-sql

我有一个架构的数据框(business_df):

|-- business_id: string (nullable = true)
|-- categories: array (nullable = true)
|    |-- element: string (containsNull = true)
|-- city: string (nullable = true)
|-- full_address: string (nullable = true)
|-- hours: struct (nullable = true)
|-- name: string (nullable = true)

我想创建一个新的数据框(new_df),以便'name'列中的值不包含任何空格。

我的代码是:

from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql import HiveContext
from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import StringType

udf = UserDefinedFunction(lambda x: x.replace(' ', ''), StringType())
new_df = business_df.select(*[udf(column).alias(name) if column == name else column for column in business_df.columns])
new_df.registerTempTable("vegas")
new_df.printSchema()
vegas_business = sqlContext.sql("SELECT stars, name from vegas limit 10").collect()

我一直收到这个错误:

NameError: global name 'replace' is not defined

这段代码有什么问题?

5 个答案:

答案 0 :(得分:9)

虽然您所描述的问题无法通过提供的代码重现,但使用Python UDFs来处理这样的简单任务,效率相当低。如果您只想从文本中删除空格,请使用regexp_replace

from pyspark.sql.functions import regexp_replace, col

df = sc.parallelize([
    (1, "foo bar"), (2, "foobar "), (3, "   ")
]).toDF(["k", "v"])

df.select(regexp_replace(col("v"), " ", ""))

如果要标准化空行,请使用trim

from pyspark.sql.functions import trim

df.select(trim(col("v")))

如果您想保留领先/尾随空格,可以调整regexp_replace

df.select(regexp_replace(col("v"), "^\s+$", ""))

答案 1 :(得分:2)

正如@ zero323所说,可能是你在某处重叠replace函数。我测试了你的代码,它运行得很好。

from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql import HiveContext
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

df = sqlContext.createDataFrame([("aaa 111",), ("bbb 222",), ("ccc 333",)], ["names"])
spaceDeleteUDF = udf(lambda s: s.replace(" ", ""), StringType())
df.withColumn("names", spaceDeleteUDF("names")).show()

#+------+
#| names|
#+------+
#|aaa111|
#|bbb222|
#|ccc333|
#+------+

答案 2 :(得分:2)

这是一个删除字符串中所有空格的函数:

import pyspark.sql.functions as F

def remove_all_whitespace(col):
    return F.regexp_replace(col, "\\s+", "")

您可以使用以下功能:

actual_df = source_df.withColumn(
    "words_without_whitespace",
    quinn.remove_all_whitespace(col("words"))
)

remove_all_whitespace功能在quinn library中定义。 quinn还定义了single_spaceanti_trim方法来管理空格。 PySpark定义了ltrimrtrimtrim方法来管理空格。

答案 3 :(得分:1)

我认为即使使用少量数据,使用regexp_replace的解决方案也太慢了!所以我试图找到另一种方法,我想我找到了!

不是很完美,有点天真,但是速度很快!你觉得呢?

def normalizeSpace(df,colName):

  # Left and right trim
  df = df.withColumn(colName,ltrim(df[colName]))
  df = df.withColumn(colName,rtrim(df[colName]))

  #This is faster than regexp_replace function!
  def normalize(row,colName):
      data = row.asDict()
      text = data[colName]
      spaceCount = 0;
      Words = []
      word = ''

      for char in text:
          if char != ' ':
              word += char
          elif word == '' and char == ' ':
              continue
          else:
              Words.append(word)
              word = ''

      if len(Words) > 0:
          data[colName] = ' '.join(Words)

      return Row(**data)

      df = df.rdd.map(lambda row:
                     normalize(row,colName)
                 ).toDF()
      return df
schema = StructType([StructField('name',StringType())])
rows = [Row(name='  dvd player samsung   hdmi hdmi 160W reais    de potencia 
bivolt   ')]
df = spark.createDataFrame(rows, schema)
df = normalizeSpace(df,'name')
df.show(df.count(),False)

打印

+---------------------------------------------------+
|name                                               |
+---------------------------------------------------+
|dvd player samsung hdmi hdmi 160W reais de potencia|
+---------------------------------------------------+

答案 4 :(得分:1)

如@Powers所示,它有一个非常好用且易于阅读的功能,用于删除称为quinn的软件包提供的空格。您可以在以下位置找到它:https://github.com/MrPowers/quinn以下是有关如何安装它的说明:在Data Bricks工作空间上工作:https://docs.databricks.com/libraries.html

再次说明其工作原理:

#import library 
import quinn

#create an example dataframe
df = sc.parallelize([
    (1, "foo bar"), (2, "foobar "), (3, "   ")
]).toDF(["k", "v"])

#function call to remove whitespace. Note, withColumn will replace column v if it already exists
df = df.withColumn(
    "v",
    quinn.remove_all_whitespace(col("v"))
)

输出: enter image description here