Pyspark 基于现有数据帧的条件创建新的spark数据帧
我想根据条件从现有数据帧创建一个新的数据帧 df1=> 这里,如果df1中的id2按字母顺序大于k,则新数据帧df2应如下所示: df2=>Pyspark 基于现有数据帧的条件创建新的spark数据帧,pyspark,Pyspark,我想根据条件从现有数据帧创建一个新的数据帧 df1=> 这里,如果df1中的id2按字母顺序大于k,则新数据帧df2应如下所示: df2=> 使用F.when: df.withColumn("id2", F.when(col("id2")>"k", 1).otherwise(0)).show() +---+---+
使用
F.when
:
df.withColumn("id2", F.when(col("id2")>"k", 1).otherwise(0)).show()
+---+---+
|id1|id2|
+---+---+
| 11| 0|
| 11| 0|
| 20| 1|
| 20| 1|
| 20| 1|
| 31| 0|
| 31| 0|
+---+---+
.distinct()
如果要重复数据消除
id1 id2
11 0
20 1
31 0
df.withColumn("id2", F.when(col("id2")>"k", 1).otherwise(0)).show()
+---+---+
|id1|id2|
+---+---+
| 11| 0|
| 11| 0|
| 20| 1|
| 20| 1|
| 20| 1|
| 31| 0|
| 31| 0|
+---+---+