代码之家  ›  专栏  ›  技术社区  ›  User12345

pyspark数据帧将false和true转换为0和1

  •  0
  • User12345  · 技术社区  · 6 年前

    我在Pyspark里有一个数据帧

    df.show()
    
    
    +-----+-----+
    |test1|test2|
    +-----+-----+
    |false| true|
    | true| true|
    | true|false|
    |false| true|
    |false|false|
    |false|false|
    |false|false|
    | true| true|
    |false|false|
    +-----+-----+
    

    我想把所有的 false 数据帧中的值 0 true to 1

    我在下面这样做

    df1 = df.withColumn('test1', F.when(df.test1 == 'false', 0).otherwise(1)).withColumn('test2', F.when(df.test2 == 'false', 0).otherwise(1))
    

    我得到了我的结果。但我想也许有更好的办法。

    3 回复  |  直到 6 年前
        1
  •  3
  •   Alper t. Turker    6 年前

    使用 CASE ... WHEN ( when(...).otherwise(...) )是不必要的冗长。相反,你可以 cast 整数:

    from pyspark.sql.functions import col
    
    df.select([col(c).cast("integer") for c ["test1", "test2"]])
    
        2
  •  1
  •   akuiper    6 年前

    一种避免多重性的方法 withColumn 尤其是当你有很多列的时候 functools.reduce 你只使用 带柱 曾经在这里:

    import pyspark.sql.functions as F
    from functools import reduce
    
    cols = ['test1', 'test2']
    reduce(lambda df, c: df.withColumn(c, F.when(df[c] == 'false', 0).otherwise(1)), cols, df).show()
    +-----+-----+
    |test1|test2|
    +-----+-----+
    |    1|    0|
    |    0|    1|
    +-----+-----+
    
        3
  •  0
  •   mahmoud mehdi    6 年前

    对于scala用户:

    df.withColumn('new', col("test1").isNotNull.cast(IntegerType))
    

    我希望有帮助。