【问题标题】:Replace string field columns with null when field value is empty or len(field.stripe(' \t')) == 0当字段值为空或 len(field.stripe(' \t')) == 0 时,将字符串字段列替换为 null
【发布时间】:2017-10-22 09:17:52
【问题描述】:
%spark.pyspark
l = [('user1', 33, 1.0, 'chess'), ('user2', 34, 2.0, 'tenis'), ('user3', None, None, ''), ('user4', None, 4.0, '   '), ('user5', None, 5.0, 'ski')]
df = spark.createDataFrame(l, ['name', 'age', 'ratio', 'hobby'])
df.show()

root
 |-- name: string (nullable = true)
 |-- age: long (nullable = true)
 |-- ratio: double (nullable = true)
 |-- hobby: string (nullable = true)
+-----+----+-----+-----+
| name| age|ratio|hobby|
+-----+----+-----+-----+
|user1|  33|  1.0|chess|
|user2|  34|  2.0|tenis|
|user3|null| null|     |
|user4|null|  4.0|     |
|user5|null|  5.0|  ski|
+-----+----+-----+-----+

当字段值为空或 len(field.stripe(' \t')) == 0 时,我想用 null 替换字符串字段列。在我的情况下,“爱好”列空槽应该替换为空值。有什么提示吗?

【问题讨论】:

    标签: apache-spark dataframe pyspark apache-zeppelin


    【解决方案1】:

    你可以把空的bu null填成

    df.withColumn("hobby", blank_as_null("hobby"))
    

    用于检查len(field.stripe(' \t')) == 0 你可以使用UDF

    def replace(column, value):
        return when(len(column.stripe(' \t')) == 0, column).otherwise(lit(None))
    
    df.withColumn("y", replace(col("y"), null)).show()
    

    【讨论】:

    • 对不起,但它不起作用: def replace(column, value): return when(len(column.stripe(' \t')) == 0, column).otherwise(lit( None)) df.withColumn('hobby', replace(col('hobby'), null)).show() NameError: name 'null' is not defined 用 None 替换 null 也不起作用。
    猜你喜欢
    • 2014-08-10
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2014-03-04
    相关资源
    最近更新 更多