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

标签 dataframe apache-spark pyspark 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

这段代码有什么问题?

最佳答案

虽然您所描述的问题无法通过提供的代码重现,但使用 Python UDF 处理此类简单任务的效率相当低。如果您只想从文本中删除空格,请使用 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+$", ""))

关于dataframe - 从 Spark 中的数据框列值中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540974/

相关文章:

pandas - 在 pandas 数据框中特定条件下删除其余数据

scala - 使用 Datastax 的 Spark Cassandra Connector 在 TableDef 上设置 Cassandra 聚类顺序

python - Spark Python - 如何使用按键归约来获取最小值/最大值

python - Pyspark Dataframe 选择少数列上带有别名的所有列

r - 按组计算时间的相对变化

python - 如何在Python中的日期时间索引值之间聚合具有一致时间增量的Pandas DataFrame行?

python-3.x - py4JJava 错误 - 使用 select 语句时出错

python - Spark Streaming 不从本地目录读取

Python:如何从 Pandas 系列的字典中获取值

apache-spark - 按列保护 Parquet 文件