dataframe - 如何根据其他列的条件用另一列的值填充 pyspark 数据框中的列
问题描述
任何人都可以在下面的链接上回答问题,但在 pyspark 中?
我在这里再次重复这个问题:
假设我们在 pyspark 中有一个数据框,如下所示:
col1 | col2 | col3 | col4
22 | null | 23 | 56
12 | 54 | 22 | 36
48 | null | 2 | 45
76 | 32 | 13 | 6
23 | null | 43 | 8
67 | 54 | 56 | 64
16 | 32 | 32 | 6
3 | 54 | 64 | 8
67 | 4 | 23 | 64
我想col4
用col1
ifcol4<col1
和col2
is not替换的值null
所以结果应该是
col1 | col2 | col3 | col4
22 | null | 23 | 56
12 | 54 | 22 | 36
48 | null | 2 | 45
76 | 32 | 13 | 76
23 | null | 43 | 8
67 | 54 | 56 | 67
16 | 32 | 32 | 16
3 | 54 | 64 | 8
67 | null | 23 | 64
任何帮助,将不胜感激。
解决方案
这解决了你的问题:
from pyspark.sql.functions import col, when
condition_col = (col('col4') < col('col1')) & (col('col2').isNotNull())
df = df.withColumn('col4', when(condition_col, col('col1')).otherwise(col('col4')))
when(cond, result1).otherwise(result2)
像带有列的 if / else 子句一样工作。
对于列逻辑运算符,请使用:&
for and
; |
对于or
; ~
为not
.