我有一个模式的数据框(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/