Use*_*345 1 python apache-spark pyspark
我在 Pyspark 中有一个数据框
df.show()
+-----+-----+
|test1|test2|
+-----+-----+
|false| true|
| true| true|
| true|false|
|false| true|
|false|false|
|false|false|
|false|false|
| true| true|
|false|false|
+-----+-----+
Run Code Online (Sandbox Code Playgroud)
我想将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))
Run Code Online (Sandbox Code Playgroud)
我得到了我的结果。但我认为可能有更好的方法来做到这一点。
使用CASE ... WHEN( when(...).otherwise(...)) 是不必要的冗长。相反,你可以只是cast整数:
from pyspark.sql.functions import col
df.select([col(c).cast("integer") for c ["test1", "test2"]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5661 次 |
| 最近记录: |