如何通过 pyspark 删除字符串中的每个 space?
how to remove every space inside string by pyspark?
df1 = spark.read.csv('/content/drive/MyDrive/BigData2021/Lecture23/datasets/cities.csv', header = True, inferSchema= True)
import pyspark.sql.functions as F
for name in df1.columns:
df1 = df1.withColumn(name, F.trim(df1[name]))
df1.show()
这是我的一段代码,我尝试 trim 列 header 中的每个 space 以及值,但它不起作用我需要函数来使用所有其他 df。
您可以使用 regexp_replace
将列值中的空格替换为空字符串 ""
。
您可以使用 replace
删除列名中的空格。
from pyspark.sql import functions as F
df = spark.createDataFrame([("col1 with spaces ", "col 2 with spaces", ), ], ("col 1", "col 2"))
"""
+------------------+-----------------+
| col 1| col 2|
+------------------+-----------------+
|col1 with spaces |col 2 with spaces|
+------------------+-----------------+
"""
select_expr = [F.regexp_replace(F.col(c), "[\s]", "").alias(c.replace(" ", "")) for c in df.columns]
df.select(*select_expr).show()
"""
+--------------+--------------+
| col1| col2|
+--------------+--------------+
|col1withspaces|col2withspaces|
+--------------+--------------+
"""
df1 = spark.read.csv('/content/drive/MyDrive/BigData2021/Lecture23/datasets/cities.csv', header = True, inferSchema= True)
import pyspark.sql.functions as F
for name in df1.columns:
df1 = df1.withColumn(name, F.trim(df1[name]))
df1.show()
这是我的一段代码,我尝试 trim 列 header 中的每个 space 以及值,但它不起作用我需要函数来使用所有其他 df。
您可以使用 regexp_replace
将列值中的空格替换为空字符串 ""
。
您可以使用 replace
删除列名中的空格。
from pyspark.sql import functions as F
df = spark.createDataFrame([("col1 with spaces ", "col 2 with spaces", ), ], ("col 1", "col 2"))
"""
+------------------+-----------------+
| col 1| col 2|
+------------------+-----------------+
|col1 with spaces |col 2 with spaces|
+------------------+-----------------+
"""
select_expr = [F.regexp_replace(F.col(c), "[\s]", "").alias(c.replace(" ", "")) for c in df.columns]
df.select(*select_expr).show()
"""
+--------------+--------------+
| col1| col2|
+--------------+--------------+
|col1withspaces|col2withspaces|
+--------------+--------------+
"""