【问题标题】:PySpark: how to convert blank to null in one or more columnsPySpark:如何在一列或多列中将空白转换为空
【发布时间】:2022-06-11 07:22:50
【问题描述】:

对于 DataFrame,我需要将空白字符串(''' '、...)转换为一组列中的空值。

df = spark.createDataFrame([
  ('ball', 'medium', '', 'blue'),
  ('pencil', 'small', '5g', ''),
  ('paper', ' ', ' ', 'white')
], ['product', 'size', 'weight', 'color'])

我可以为每一列一一做,但是当我们有很多数据框和列时,它就太懒了。

from pyspark.sql.functions import when, trim, col

df = df \
 .withColumn('size', when(trim(col('size')) == '', None).otherwise(col('size'))) \
 .withColumn('weight', when(trim(col('weight')) == '', None).otherwise(col('weight'))) \
 .withColumn('color', when(trim(col('color')) == '', None).otherwise(col('color')))

我应该如何以更通用的方式进行转换,避免代码复制?

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql databricks


    【解决方案1】:

    您可以封装在一个函数中并用它覆盖DataFrame类

    from pyspark.sql.functions import when, trim, col
    from pyspark.sql.dataframe import DataFrame
    
    def blank_to_null(self, *col_names):
      for col_name in col_names:
         self = self.withColumn(
           col_name,
           when(trim(col(col_name)) == '', None) \
           .otherwise(col(col_name)))
      return self
    
    DataFrame.blank_to_null = blank_to_null
    

    现在很简单

    df = df.blank_to_null('size', 'weight', 'color')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 2020-04-29
      相关资源
      最近更新 更多